Different ways of Loading Javascript Files in a Javascript File


JS Different ways of Loading Javascript Files in a Javascript File javascript

NodeJs / Javascript

The javascript (in HTML, the browser DOM i.e. Document Object Model) does not have a inbuilt/inherent @include method/function that allwos us to load dynamically another Javascript file/lib. But this is totally possible via the following method (document.createElement):

We can use document.write method to load Javscript code, but this has many drawbacks: one biggest drawback is that the document will be reset once it is loaded. Thus this method is not recommended.

Load JS code via document.createElement

We can use the following code to load it and append it to the head:

1
2
3
4
5
var js = document.createElement('script');
js.src = 'anotherScript.js';
document.getElementsByTagName('head')[0].appendChild(js);
// or the following is also ok.
// document.head.appendChild(js);
var js = document.createElement('script');
js.src = 'anotherScript.js';
document.getElementsByTagName('head')[0].appendChild(js);
// or the following is also ok.
// document.head.appendChild(js);

Use the following to load the javascript into the body tag:

1
2
3
var js = document.createElement('script');
js.src = 'anotherScript.js';
document.body.appendChild(js);
var js = document.createElement('script');
js.src = 'anotherScript.js';
document.body.appendChild(js);

However, if you load the code at head tag then the document.body is not accessible yet.

The document.documentElement is always existent because it is the html document itself, we can use this to load JS code:

1
2
3
4
var js = document.createElement('script');
js.src = 'anotherScript.js';
var html = document.documentElement;
html.insertBefore(js, html.firstChild);
var js = document.createElement('script');
js.src = 'anotherScript.js';
var html = document.documentElement;
html.insertBefore(js, html.firstChild);

We can use the following code to load another JS code before the first script tag.

1
2
3
4
var js = document.createElement('script');
js.src = 'anotherScript.js';
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(js, first);
var js = document.createElement('script');
js.src = 'anotherScript.js';
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(js, first);

If there is no script on the HTML page, it will not work although.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
403 words
Last Post: Teaching Kids Programming - Divide and Conquer Algorithm Explained (Max Number, Ruler Marker)
Next Post: Teaching Kids Programming - Estimating the Performance Speedup (Gain) using Amdahls Law

The Permanent URL is: Different ways of Loading Javascript Files in a Javascript File

Leave a Reply