Resource loading: onload and onerror
The browser allows us to track the loading of external resources – scripts, iframes, pictures and so on. There are two events for it: - onload – successful load, - onerror – an error occurred.
Loading a script
Let’s say we need to load a third-party script and call a function that resides there. We can load it dynamically, like this: …But how to run the function that is declared inside that script? We need to wait until the script loads, and only then we can call it.
script.onload
The main helper is the load event. It triggers after the script was loaded and executed. For instance: So in onload we can use script variables, run functions etc. …And what if the loading failed? For instance, there’s no such script (error 404) or the server is down (unavailable).
script.onerror
Errors that occur during the loading of the script can be tracked in an error event. For instance, let’s request a script that doesn’t exist: Please note that we can’t get HTTP error details here. We don’t know if it was an error 404 or 500 or something else. Just that the loading failed.
Other resources
The load and error events also work for other resources, basically for any resource that has an external src.
For example:
There are some notes though:
- Most resources start loading when they are added to the document. But is an exception. It starts loading when it gets a src (*).
- For
Crossorigin policy
There’s a rule: scripts from one site can’t access contents of the other site. So, e.g. a script at https://facebook.com can’t read the user’s mailbox at https://gmail.com. Or, to be more precise, one origin (domain/port/protocol triplet) can’t access the content from another one. So even if we have a subdomain, or just another port, these are different origins with no access to each other. This rule also affects resources from other domains. If we’re using a script from another domain, and there’s an error in it, we can’t get error details. For example, let’s take a script error.js that consists of a single (bad) function call: Now load it from the same site where it’s located: We can see a good error report, like this: Now let’s load the same script from another domain: The report is different, like this: Details may vary depending on the browser, but the idea is the same: any information about the internals of a script, including error stack traces, is hidden. Exactly because it’s from another domain. Why do we need error details? There are many services (and we can build our own) that listen for global errors using window.onerror, save errors and provide an interface to access and analyze them. That’s great, as we can see real errors, triggered by our users. But if a script comes from another origin, then there’s not much information about errors in it, as we’ve just seen. Similar cross-origin policy (CORS) is enforced for other types of resources as well. To allow cross-origin access, the