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.
Related posts:
- Assigning objects by value in Javascript Javascript can be a little bit of a quirky language...
- How browser incompatibility can waste my day I got struck by a curious problem the other day....
- Better JavaScript error handling with DamnIT We all know that the Internet is a mess, with...
- Javascript error handling idiosyncrasies If there is one thing that can drive me insane...
- PHP functionality from within Javascript Most PHP programmers have to deal with Javascript in some...
Related posts brought to you by Yet Another Related Posts Plugin.
Serge Meunier is a software developer living in Cape Town, South Africa. He loves programming, fencing, philosophy, feeding his internet addiction, and, of course, dogs.
Comments