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;
}
Thank you
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/en-US/docs/Web/API/HTMLScriptElement
Thank you
Share Improve this question asked Jun 4, 2019 at 19:07 bressonbresson 90111 silver badges20 bronze badges 02 Answers
Reset to default 7onload
's callback is called when these have been pleted:
- The HTTP request to fetch the script file has been pleted successfully
- The script content has been parsed
- The script has been executed, thus possibly exposing new global variables and/or triggering side effects like DOM manipulation or XHR
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./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 menting 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.
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.