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.
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.
Share Improve this question edited Sep 6, 2014 at 15:21 user4014548 asked Sep 6, 2014 at 14:04 Oleg PatrushevOleg Patrushev 631 silver badge4 bronze badges 1- 2 require(url, callback) { ... e.onload = callback } – eosterberg Commented Sep 6, 2014 at 14:07
2 Answers
Reset to default 17You 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
});