How to include a JavaScript file inside a JavaScript file?

by Yang Yang on July 22, 2010

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:

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

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.

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

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.

bob October 12, 2010 at 5:21 am

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

Yang Yang October 14, 2010 at 8:01 am

Nice one, thanks bob!

Thomas S August 3, 2011 at 6:25 am

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.

Arun November 9, 2011 at 5:27 pm

Hi,

Thanks for providing the such a useful information. It was very help full.

Regards
Arun

well well October 30, 2012 at 2:26 pm

you can write this in the A.js javascript file…
$(‘head’).append(”);

Rutul February 4, 2013 at 9:10 pm

function includeJS(incFile)
{
document.write(”);
}

Then include a second JavaScript file by calling:

includeJS(‘filename.js’);

Comments on this entry are closed.

Previous post:

Next post: