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.
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:
<img>
is an exception. It starts loading when it gets a src (*)
.<iframe>
, the iframe.onload
event triggers when the iframe loading finished, both for successful load and in case of an error.