Run JavaScript After the DOM Is Ready

When a script queries an element before the browser has parsed that element, selectors return null and later property access fails. For an external script that depends on page markup, add defer. The browser downloads it without blocking HTML parsing and executes it after the document has been parsed.

Last updated: October 5, 2026.

<img id="featured-image" src="placeholder.png" alt="Featured item">

<script defer src="gallery.js"></script>

<!-- gallery.js -->
<script>
const images = ['photo-1.png', 'photo-2.png', 'photo-3.png'];
const image = document.querySelector('#featured-image');
const index = Math.floor(Math.random() * images.length);

image.src = images[index];
</script>

In a real page, keep the JavaScript in gallery.js; the inline block above only shows its contents. Because the external script is deferred, #featured-image exists before the selector runs. This remains safe when the script tag is placed in the document head. A module script has deferred behavior by default.

Use DOMContentLoaded for code loaded in other ways

If a script can be injected dynamically or loaded with async, it may execute before or after the event. Check document.readyState: run immediately when parsing has finished, otherwise attach one DOMContentLoaded listener. MDN’s DOMContentLoaded reference documents this timing and notes that the event does not wait for images to finish loading.

Avoid combining several readiness techniques around the same initialization function. That can run setup twice and attach duplicate event handlers.

Wait for load only when resource dimensions matter

Use the image element’s load event when code needs its natural width or decoded pixels. Do not delay ordinary DOM setup until window.load; that event waits for images and other dependent resources and is usually later than necessary.

The MDN script element guide compares normal, async, defer, and module execution. For related fundamentals, review your first JavaScript program, tracing an error to its source, and JavaScript functions.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov