最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - <script> onload fires when ...? - Stack Overflow

programmeradmin4浏览0评论

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 0
Add a ment  | 

2 Answers 2

Reset to default 7

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

  1. The HTTP request to fetch the script file has been pleted 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./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.

发布评论

评论列表(0)

  1. 暂无评论