How to include a JavaScript file in another JavaScript file

There are two main ways to achieve this:

1 – You can load it with an Ajax call and then use eval.

This is the most straightforward way, but it’s limited to your domain because of the JavaScript safety settings, and using eval is opening the door to bugs and hacks.

2 – Add a script tag with the script URL in the HTML.

This is definitely the best way to go. You can load the script even from a foreign server, and it’s clean as you use the browser parser to evaluate the code. You can put the <script /> tag in the head of the web page, or at the bottom of the body.

Both of these solutions are discussed and illustrated in JavaScript Madness: Dynamic Script Loading.

Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance.

It means that if you use these tricks directly, you won’t be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.

For example: my_lovely_script.js contains MySuperObject:

var js = document.createElement("script");

js.type ="text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);var s =newMySuperObject();Error:MySuperObjectisundefined

Then you reload the page hitting F5. And it works! Confusing…

So what to do about it ?

Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses en event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. For example:

function loadScript(url, callback){// Adding the script tag to the head as suggested beforevar head = document.getElementsByTagName('head')[0];var script = document.createElement('script');
    script.type ='text/javascript';
    script.src = url;// Then bind the event to the callback function.// There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;// Fire the loading

Then you write the code you want to use AFTER the script is loaded in a lambda function:

var myPrettyCode =function(){// Here, do what ever you want};

Then you run all that:

loadScript("my_lovely_script.js", myPrettyCode);

OK, I got it. But it’s a pain to write all this stuff.

Well, in that case, you can use as always the fantastic free jQuery library, which let you do the very same thing in one line:


   alert("Script loaded and executed.");// Here you can use anything you defined in the loaded script});


Source: StackOverflow Question

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.