Trying to fire the onload event on script tag
I'm trying to load a set of scripts in order, but the onload event isn't firing for me.
var scripts = [
'//cdnjs.cloudflare.com/ajax/libs/less.js/1.3.3/less.min.js',
'//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0-rc.3/handlebars.min.js',
MK.host+'/templates/templates.js'
];
function loadScripts(scripts){
var script = scripts.shift();
var el = document.createElement('script');
el.src = script;
el.onload = function(script){
console.log(script + ' loaded!');
if (scripts.length) {
loadScripts(scripts);
}
else {
console.log('run app');
MK.init();
}
};
$body.append(el);
}
loadScripts(scripts);
I guess native events like el.onload don't fire when jQuery is used to append the element to the DOM. If I use native document.body.appendChild(el)
then it fires as expected.
Solution 1:
You should set the src
attribute after the onload
event, f.ex:
el.onload = function() { //...
el.src = script;
You should also append the script to the DOM before attaching the onload
event:
$body.append(el);
el.onload = function() { //...
el.src = script;
Remember that you need to check readystate
for IE support. If you are using jQuery, you can also try the getScript()
method: http://api.jquery.com/jQuery.getScript/
Solution 2:
I faced a similar problem, trying to test if jQuery is already present on a page, and if not force it's load, and then execute a function. I tried with @David Hellsing workaround, but with no chance for my needs. In fact, the onload
instruction was immediately evaluated, and then the $
usage inside this function was not yet possible (yes, the huggly "$ is not a function." ^^).
So, I referred to this article : https://developer.mozilla.org/fr/docs/Web/Events/load and attached a event listener to my script object.
var script = document.createElement('script');
script.type = "text/javascript";
script.addEventListener("load", function(event) {
console.log("script loaded :)");
onjqloaded();
});
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
For my needs, it works fine now. Hope this can help others :)