# 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: ```js let script = document.createElement('script'); script.src = "my.js"; document.head.append(script); ``` ...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. ```smart For our own scripts we could use [JavaScript modules](info:modules) here, but they are not widely adopted by third-party libraries. ``` ### script.onload The main helper is the `load` event. It triggers after the script was loaded and executed. For instance: ```js run untrusted let script = document.createElement('script'); // can load any script, from any domain script.src = "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.3.0/lodash.js" document.head.append(script); *!* script.onload = function() { // the script creates a helper function "_" alert(_); // the function is available }; */!* ``` 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: ```js run let script = document.createElement('script'); script.src = "https://example.com/404.js"; // no such script document.head.append(script); *!* script.onerror = function() { alert("Error loading " + this.src); // Error loading https://example.com/404.js }; */!* ``` 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. ```warn 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: ```js run 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 `` is an exception. It starts loading when it gets a src `(*)`. - For `