Sentry Answers>JavaScript>

What’s the difference between the window `load` event and the document `DOMContentLoaded` event?

What’s the difference between the window `load` event and the document `DOMContentLoaded` event?

Matthew C.

The Problem

You want to run some JavaScript code after a page has loaded. Should you use the window load event or the document DOMContentLoaded event to determine when to run the code?

The Solution

The window load event is fired when the entire web page has been loaded. This includes the page DOM and all dependent resources such as scripts, stylesheets, and images.

The document DOMContentLoaded event is fired when the page DOM has been loaded and all deferred scripts have been loaded and executed.

If your JavaScript code only needs to interact with the DOM, use the DOMContentLoaded event. This can be useful if you want to modify the DOM once it’s loaded, set up event listeners, or fetch data from an API that will be displayed in the UI. For example, if you’re using a UI library, such as HighCharts, adding the UI element after the DOMContentLoaded event improves performance as it does not wait for images or CSS to be loaded before adding the chart UI element to the page:

Click to Copy
document.addEventListener('DOMContentLoaded', ()=> { Highcharts.chart('container', { // add config here }); });

If your JavaScript code depends on resources like stylesheets and images, then using the window load event is a better option. For example, if you want to start an animation only once all images have been loaded do the following:

Click to Copy
window.onload = function() { // code to run animation. HeaderTextAnimation(); };

For further reading on the order of events that happen when a page loads, learn about the Critical Rendering Path on MDN.

  • ResourcesImprove Web Browser Performance - Find the JavaScript code causing slowdowns
  • SentryJavascript Error Monitoring & Tracing
  • ResourcesJavaScript Frontend Error Monitoring 101
  • Syntax.fmListen to the Syntax Podcast
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.