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 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:
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:
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.
Get actionable, code-level insights to resolve JavaScript performance bottlenecks and errors.
Create a free Sentry account
Create a JavaScript project and note your DSN
Grab the Sentry JavaScript SDK
<script src="https://browser.sentry-cdn.com/7.112.2/bundle.min.js"></script>
Sentry.init({ dsn: 'https://<key>@sentry.io/<project>' });
Loved by over 4 million developers and more than 90,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.