script.onload, onerror

3547 단어 JavaScriptJavaScript

script.onload / script.onerror

Important:

Events onload/onerror track only the loading itself.

Errors that may occur during script processing and execution are out of scope for these events. That is: if a script loaded successfully, then onload triggers, even if it has programming errors in it. To track script errors, one can use window.onerror global handler.

Other resources

The load and error events also work for other resources, basically for any resource that has an external src.

For example:

let img = document.createElement('img');
img.src = "https://js.cx/clipart/train.gif"; // (*)

img.onload = function() {
  alert(`Image loaded, size ${img.width}x${img.height}`);
};

img.onerror = function() {
  alert("Error occurred while loading image");
};

There are some notes though:

  • Most resources start loading when they are added to the document. But <img> is an exception. It starts loading when it gets a src (*).
  • For <iframe>, the iframe.onload event triggers when the iframe loading finished, both for successful load and in case of an error.

좋은 웹페이지 즐겨찾기