How to include a JavaScript file inside a JavaScript file?

This is a pretty odd question to ask in the first place if you have been using JavaScript for a while. JavaScript files are called from HTML web pages who need them to manipulate the HTML elements so that the users have extraordinary interactive experience. You can’t include a JavaScript file inside another JavaScript file like you can with PHP files, but you can only include JS files from HTML files.

If you need something that’s in a JavaScript file such as a predefined function, just include the file before wherever you are using the function and it should be fine. For example, you are calling A.js from a HTML file:

<script type="text/javascript" src="A.js"></script>

There is a rather sophisticated function in B.js that A.js relies on. You are wondering how to include B.js in A.js so A.js works properly. No you can’t. The answer is not to include B.js in A.js but include B.js in the HTML file before it includes A.js.

<script type="text/javascript" src="B.js"></script>
<script type="text/javascript" src="A.js"></script>

Now all the code in A.js should work fine. This is because all HTML code are read, parsed and executed in basic sequence from top to bottom. It’s the same with JavaScript code. When you need something from another JavaScript file and want to use it on the web page, just include it in the HTML web page. You can’t include a JavaScript file in a JavaScript file.

6 thoughts on “How to include a JavaScript file inside a JavaScript file?”

  1. Actually you can use XMLHttpRequest to get the file and the use eval to execute the contents of the returned file in string form.

  2. Well, except thats not entirely true.

    JavaScript (aka ECMAscript) is used outside of just HTML pages. It can, for example, also be embedded in SVG documents (direct or by reference/xlink).

    So there may not be any HTML in use where a JavaScript file is used/executed. Granted, the SVG syntax for including the JavaScript files is the same as that of the HTML file.

    The lack of include capability does limit the ability of creating modular javascript code, unfortunately.

  3. function includeJS(incFile)

    Then include a second JavaScript file by calling:


Comments are closed.

Scroll to Top