I'd like to know if it is possible to include a .js
file within another .js
file?
The reason for me wanting to do this is to keep client includes to a minimum. I have several .js
files already written with functions that are needed by the client. The client would have an html file which he/she manages with a .js
file include (my .js
file).
I could re-write a new .js
file with all the functions in it or, to avoid doing double work, figure out a way to write a .js
file that includes other .js
files.
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.
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.
I basically do like this, create new element and attach that to <head>
var x = document.createElement('script'); x.src = 'http://example.com/test.js'; document.getElementsByTagName("head")[0].appendChild(x);
You may also use onload
event to each script you attach, but please test it out, I am not so sure it works cross-browser or not.
x.onload=callback_function;
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