How to Include a JavaScript File in Another JavaScript File

From WikiHTP

In JavaScript, it is not possible to import a script. Scripts are only imported into a web page via the <script> tag. This will soon be possible when the new ES6 version of JavaScript will be fully supported by browsers. In the meantime, there are alternatives for dynamically loading a JavaScript file.

Using AJAX[edit]

The simplest method is to make an AJAX call to load the script and then interpret its contents with the eval() function. This method is the most straightforward but it is limited only to the domain where the page is located and it can be hijacked to interpret malicious code.

Using jQuery getScript()[edit]

If you use the jQuery library, the jQuery library directly provides a function that performs the AJAX call and code interpretation: the getScript() function:

$.getScript (my_script_to_include.js, function () { 
    alert (The script has been successfully loaded.); 

Dynamically add a <script> tag to the page[edit]

Another solution is to dynamically add a <script> tag to the page. This solution has several advantages: it works with a different domain from the one on which the page is located and the browser interprets the script as soon as it is loaded.

// create tag 
var js = document.createElement(script); 
js.type = text/javascript; 
js.src = my_script_to_include.js; 
// Add the tag in the 

The problem with this method is that the script is loaded asynchronously, that is, the code after the last directive runs while the script is being downloaded by the browser. This can result in errors if a directive requires JavaScript code in the called script. To correct this problem, you must add a function that is linked to the script loading event. The code is thus executed when the script is fully loaded.

// create tag 
var js = document.createElement (script); 
js.type = text / javascript; 
js.src = my_script_to_include.js;

We bind the function containing our code to load the script called by the tag. Two directives are used so that the code is compatible with all browsers.

js.onreadystatechange = myNewCode; 
js.onload = myNewCode; 
// Add the tag in the 
document.body.appendChild (js) page; 
var myNewCode = function () 
   // The code here will be executed when the script has been fully downloaded 

About This Tutorial

This page was last edited on 28 January 2019, at 06:34.