The onload attribute fires when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.). However, it can be used on other elements as well (see "Supported HTML tags" below).
The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there.
In JavaScript, this event can apply to launch a particular function when the page is fully displayed. It can also be used to verify the type and version of the visitor's browser. We can check what cookies a page uses by using the onload attribute.
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/
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 :)
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