Reputation: 901
In the function below from Mozilla, JS is used to add a tag into the document. I'm confused when the onload event fires. Does onload fire when the script starts to download or has already downloaded?
function prefixScript(url, onloadFunction) {
var newScript = document.createElement("script");
newScript.onerror = loadError;
if (onloadFunction) { newScript.onload = onloadFunction; }
document.currentScript.parentNode.insertBefore(newScript, document.currentScript);
newScript.src = url;
}
https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement
Thank you
Upvotes: 5
Views: 6253
Reputation: 18473
onload
's callback is called when these have been completed:
Here's a demo where a script for jQuery library is added to <head>
, thus exposing the global variable $
created by the execution of the imported script:
const script = document.createElement('script');
script.onload = () => {
try {
$;
console.log('onload - $ is defined');
} catch(e) {
console.log('onload - $ is not defined yet');
}
}
script.src = 'https://code.jquery.com/jquery-3.3.1.js';
try {
$;
console.log('main - $ is defined');
} catch(e) {
console.log('main - $ is not defined yet');
}
document.head.appendChild(script);
Last precision - int this case, the load is triggered by appending the script to the DOM, not by script.src = ...
! Try commenting out the last line - the script never loads.
There can also be other cases where the load is triggered by script.src = ...
, for example when the script is appened to the DOM, the the .src
is set.
Upvotes: 7
Reputation: 28137
From the MDN GlobalEventHandlers.onload docs:
The load event fires when a given resource has loaded.
There is also an event for onloadstart called when loading for that resource is started.
Upvotes: -3