bresson
bresson

Reputation: 901

<script> onload fires when ...?

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

Answers (2)

Nino Filiu
Nino Filiu

Reputation: 18473

onload's callback is called when these have been completed:

  1. The HTTP request to fetch the script file has been completed successfully
  2. The script content has been parsed
  3. 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.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

XCS
XCS

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

Related Questions