I have the following function:
function require(url)
{
var e = document.createElement("script");
e.src = url;
e.type="text/javascript";
document.getElementsByTagName("head")[0].appendChild(e);
}
Which allows to dynamically load javascript at runtime, and I need to add a callback after loading some new files
For example when I
require('className.js');
and just after this call
var a = new window[className];
file has not been loaded yet, so it generates an error.
Dynamic loadingThose files can be loaded asynchronously in JavaScript. To load a JavaScript file dynamically: Create a script element. Set the src , async , and type attributes.
A JavaScript callback is a function which is to be executed after another function has finished execution. A more formal definition would be - Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function.
For loading a script file dynamically using JavaScript, the basic steps are: Create the script element. Set the src attribute on the script element to point to the file we want to load. Add the script element to the DOM.
You can add an onLoad on the script element, but beware that on some older version of IE is a bit buggy.
Taking your code as a reference :
function require(url, callback)
{
var e = document.createElement("script");
e.src = url;
e.type="text/javascript";
e.addEventListener('load', callback);
document.getElementsByTagName("head")[0].appendChild(e);
}
require("some.js", function() {
// Do this and that
});
Further to Simone Gianni 's answer, in case you want to load a set of js files, plus run a callback at the end, where you want to ensure all files have loaded, you can do it recursively as follows:
function loadList(list, i, callback)
{
require(list[i], function()
{
if(i < list.length-1)
{
loadList(list, i+1, callback);
}
else
{
callback();
}
});
}
Call with:
loadList(jsList, 0, function()
{
// code that applies after all URLs in jsList have loaded
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With