Skip to content

JavaScript Resource Loading: onload and onerror

In the dynamic world of web development, mastering JavaScript is a pivotal step for enhancing website functionality and user interaction. One crucial aspect of JavaScript that developers must understand is managing resource loading. This guide delves into the methods onload and onerror, providing clear examples and practical tips to efficiently handle resources like images, scripts, and more.

Handling Resource Loading with the onload Event

What is the onload Event?

The onload event in JavaScript is triggered when a resource has fully loaded. This includes images, scripts, stylesheets, and other media files. It is particularly useful when actions need to be taken only after the complete loading of resources.

Example: Displaying an Image After Full Load

To illustrate, consider a scenario where you want to display an image only after it is fully loaded to avoid showing a partial or broken image.


html
<div>Here you see the w3docs logo when the page is loaded.</div>
<br />
<div id="imageContainer" style="background-color: grey;"></div>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var img = new Image();
    img.onload = function() {
        document.getElementById('imageContainer').appendChild(img);
    };
    img.src = 'https://www.w3docs.com/build/images/logo-color-w3.png';
});
</script>

This script ensures that the image is appended to the #imageContainer div only after it has completely loaded, enhancing the user experience by preventing the display of an incomplete image.

Utilizing the onerror Event for Error Handling

What is the onerror Event?

The onerror event is essential for robust web development. It triggers when an error occurs during the loading of an external resource, such as a script or an image. This event is crucial for handling errors gracefully and ensuring that the user experience remains uninterrupted.

Example: Error Handling for a Failed Image Load

Consider a scenario where an image fails to load due to a broken link or server issue. Using the onerror event, you can provide a fallback solution or notify the user. In the following example, you'll receive the customized error alert we made as soon as you open the "try it yourself" page, because the image link provided is not a real one.


html
<div>If there was no error, you could see an image below. But it's a broken link!</div>
<br />
<div id="imageContainer" style="background-color: grey;"></div>
<script>
const img = new Image();
const imageContainer = document.getElementById('imageContainer');
img.onerror = function() {
    imageContainer.innerHTML = 'An error happened.';
};
img.onload = function() {
    imageContainer.appendChild(img);
};
img.src = 'https://www.w3docs.com/build/images/broken-link.png';
</script>

In this example, if the image fails to load, the user is alerted with a message, thereby improving the user experience by handling the error transparently.

Example: Loading a Script or Stylesheet

The same pattern applies to <script> and <link> elements. You can create them dynamically and attach onload/onerror handlers:

html
<script>
function loadScript(url) {
    const script = document.createElement('script');
    script.src = url;
    script.onload = () => console.log('Script loaded successfully');
    script.onerror = () => console.error('Failed to load script');
    document.head.appendChild(script);
}
loadScript('https://example.com/app.js');

function loadStylesheet(url) {
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = url;
    link.onload = () => console.log('Stylesheet loaded successfully');
    link.onerror = () => console.error('Failed to load stylesheet');
    document.head.appendChild(link);
}
loadStylesheet('https://example.com/styles.css');
</script>

Optimizing Web Performance Through Event Handling

Optimizing web performance involves managing resource loading sequences and handling failures gracefully. The onload and onerror events are particularly valuable for dynamic resource injection. Instead of hardcoding all assets in the HTML, you can load non-critical resources on demand. When a resource fails to load, the onerror event triggers, allowing you to implement fallback logic—such as swapping a broken image for a placeholder or retrying a failed script request. By combining these events with progressive rendering, you ensure that critical content appears immediately while secondary assets load in the background, maintaining a smooth user experience even under poor network conditions.

Conclusion

Understanding and implementing the onload and onerror events in JavaScript are fundamental for any web developer looking to improve the reliability and performance of their web applications. By employing these events effectively, developers can ensure that resources are managed efficiently, improving both the performance and user experience of their websites. The examples provided offer a starting point for implementing these techniques in various scenarios, fostering a deeper understanding and mastery of resource loading in JavaScript.

Practice

What are the tasks that the 'onload' and 'onerror' events in Javascript handle?

Dual-run preview — compare with live Symfony routes.