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.
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.
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.
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 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.
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');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With