Most people are very familiar of including Javascript in an HTML page using the <script type=”text/javascript”> tag, such as

   <script src="js/test.js" language="Javascript"></script>

Now, that much is pretty straight-forward. But less people know that Javascript can also load other Javascript files on the fly.

So as an example of this, you can write:

   function loadJSFile(fileName) {
      document.write("<script src="+fileName+"></script>");
   }

   var fileToLoad = 'test.js';
   var secondFileToLoad = 'test2.js';

   loadJSFile(fileToLoad);
   loadJSFile(secondFileToLoad);

This works wonderfully, however, there is something to watch out for when loading multiple files this way, like in the example above.

If the second file has variables which are declared in the first file, the second file might not be able to find a reference for it. The reason for this is that since Javascript runs functions asynchronously, it means that the first file might not be loaded before the second, and thus the reference might not exist yet.

The solution to this is to write the above example so:

   function loadJSFile(fileName) {
      document.write("<script src="+fileName+"></script>");
   }

   var fileToLoad = 'test.js';
   var secondFileToLoad = 'test2.js';

   loadJSFile(fileToLoad);

   function continueLoading() {
      loadJSFile(secondFileToLoad);
   }

Then at the end of the first file, add a call to continueLoading(), and the Javascript will load as expected.

And have no fear that the scope of the variables in the Javascript file will end up in the continueLoading() scope. The scope of the variables will be in the global scope as they should be.

Share