www.cryer.co.uk
Brian Cryer's Web Resources

How one JavaScript file can cause another JavaScript file to be included

It is possible for one JavaScript file to cause another JavaScript file to be included. Whilst the logic for including one JavaScript file from anther is simple and straight forward there is an important "gotcha" with this technique, so be sure to read all the notes on this page before you use the technique.

Why would you want to include one JavaScript file from another? There are many possible reasons. A common reason is when using adverts (or trackers) on a web-page and you have been supplied with some JavaScript to include but would rather include a reference to a single external file rather than include a block of JavaScript.

How to include one JavaScript file from another

To include some JavaScript from an HTML file is simply:

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

where "external.js" is the name of (or the full path name to) the JavaScript file.

To allow that external JavaScript file to cause another to be included, add the following function to that first external JavaScript file:

<script type="text/javascript">
// Function to allow one JavaScript file to be included by another.
// Copyright (C) 2006-08 www.cryer.co.uk
function IncludeJavaScript(jsFile)
{
  document.write('<script type="text/javascript" src="'
    + jsFile + '"></scr' + 'ipt>'); 
}
</script>

and then to include a second JavaScript file simply add the line:

IncludeJavaScript('secondJS.js');

You can use this technique to include as many JavaScript files as you like.

What the "IncludeJavaScript" function is doing is generating the HTML to include the JavaScript file. The browser when it comes to render the page will read and execute the JavaScript in the first external file. This includes the line "IncludeJavaScript('secondJS.js');", which generates additional HTML. The browser will then parse the newly generated HTML which is when it picks up the references to the new JavaScript files and so on.

The reason for having "</scr' + 'ipt>" instead of "</script>" in the document.write in the script is simply that IE 7 would interpret "</script>" as the end of the script, even though it is enclosed in quotes and is part of a string. Breaking "</script>" into two parts gets round this problem.

Gotchas

There is only one gotcha with this technique, but it has may implications. The important thing to be aware of is that it is the browser which is including the JavaScript files not the JavaScript itself. Because of this:

Compatibility

The contents of this article have been tested with: