I am writing some JavaScript files that will not be used with HTML documents. For example, writing a calculator in one JavaScript file, where I'll have different .js
files say one for addition, subtraction, multiplication, division, etc..
I'd like to have each math operation in a self contained .js
file then have another .js
file that will #include the other smaller files and can call the functions from them?
Is that possible?
We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require, jQuery's getScript function, and Fetch Loading.
You can write your JS in separate files, but when it comes to deploying, it's more efficient to minify them all into a single file. For each script you load in your browser, you make a round-trip to the server, so it makes sense to minimize those.
You can keep the JavaScript code in a separate external file and then point to that file from your HTML document.
Using javascript:
var script = document.createElement('script');
script.src = '/js/script';
document.head.appendChild(script);
Using jQuery:
//you need to change your path
$.getScript('/js/script.js', function()
{
// script is imported
});
Here is a synchronous version:
function myRequire( url ) {
var ajax = new XMLHttpRequest();
ajax.open( 'GET', url, false ); // <-- the 'false' makes it synchronous
ajax.onreadystatechange = function () {
var script = ajax.response || ajax.responseText;
if (ajax.readyState === 4) {
switch( ajax.status) {
case 200:
eval.apply( window, [script] );
console.log("script loaded: ", url);
break;
default:
console.log("ERROR: script not loaded: ", url);
}
}
};
ajax.send(null);
}
Note that to get this working cross-domain, the server will need to set allow-origin header in its response.
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