Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include javascript files server-side?

I want to include JS file inside another JS file, on server side, to prevent copy-paste and multiple JS files loading from client. Just like include('file.js') as PHP would do.

like image 912
Moe Sweet Avatar asked Oct 14 '11 08:10

Moe Sweet


People also ask

Can you use JavaScript on server side?

js is a runtime environment to allow JavaScript to not only be run in the browser, but also on the server (or almost any environment, really). That also expanded the types of applications that could be built with the language since it wasn't tied to only the client-side anymore.

How do you include a JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Where do I put JavaScript files?

JavaScript in <head> or <body> You can place any number of scripts in an HTML document. Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.

How JavaScript is executed on server side?

How Does JavaScript Run On A Server? Node. js works on a v8 environment – it is a virtual machine or a JavaScript engine that runs the JavaScript code, so for hosting you can't use the ordinary web hosts. You will need the ones that have the v8 environment.


2 Answers

There is no built in way to include other JavaScript files from a JavaScript file ... but you can add them into the DOM ->

function addJavascript(jsname,pos) {
  var th = document.getElementsByTagName(pos)[0];
  var s = document.createElement('script');
  s.setAttribute('type','text/javascript');
  s.setAttribute('src',jsname);
  th.appendChild(s);
}

Example usage :

addJavascript('newExternal.js','body');
like image 143
Manse Avatar answered Nov 15 '22 10:11

Manse


As Supercharging javascript article suggest - with PHP you can read all your .js files and create one big js file that you will send in one piece.

This is a simplification of the example from the article, just to get you started:

<?php 
define('SCRIPT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/script/');

$files = array(
    'jquery.js',
    'myLib.js',
    'site.js'
);

header('Content-Type: text/javascript');
foreach (files as $file) {
    if (@readfile(SCRIPT_DIR . $file) === false) {
        error_log("javascript.php: Error reading file '$file'");
    }
}
?>

I would also recommend to read the full article Supercharging JavaScript in PHP to get more info.

like image 32
Christian P Avatar answered Nov 15 '22 10:11

Christian P