Including a JavaScript file in another JavaScript file

Here I will describe the way of including a JavaScript file in another JavaScript file. Because sometimes we need dynamic loading of JavaScript, may be based on some condition. In Css, We have already @import to include one css file into another.
But there isn’t any import, include or require in JavaScript, but there are two main ways to achieve this.

1. We can load it with an Ajax call and then use eval.
It is the most straightforward and simple way, but it’s limited to our 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.
It is definitely the best way to go. We can load the script even from a another server, and it’s clean as we use the browser parser to evaluate the code. We can put the


tag in the head of the web page, or at the bottom of the body.

For including javascript file at the bottom of the body.

For including javascript file in the head tag of the page.

Note: By implementing this means that we remotely load the code. Modern web browsers will load the file and keep executing our current script because they load everything asynchronously to improve performance.

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

Example: Due to asynchronously loading the file, next line code of using MyObject is giving error ‘Myobject is undefined’.

But If we refresh the page then It won’t give us this error.
So we can resolve this issue using callback like the ajax. We can use en event to run a callback function when the script is loaded. So we can put all the code in the callback function.

3. Using jQuery getScript method

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.