Explain Codes LogoExplain Codes Logo

Vanilla JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

javascript
prompt-engineering
functions
callbacks
Anton ShumikhinbyAnton Shumikhin·Mar 9, 2025
TLDR

Kickstart with document.addEventListener and DOMContentLoaded to nail down a vanilla JavaScript equivalent for DOM readiness:

document.addEventListener('DOMContentLoaded', () => { // Your DOM ready code lives here. });

This baby fires up when the HTML document is fully loaded, parsed, and ready to roll without waiting for extra calories, aka stylesheets, images, and subframes to complete loading - the exact mantra of jQuery’s $(document).ready().

Self-Initiating function // DOM's bottom dweller

Plant a self-invoking function at the tail of your document for an ultra-light approach:

(function() { // Some DOM action in the making. Where's the popcorn? })();

Nest it before the </body> tag and voilà, it acts pretty much like $(document).ready().

Fail-safe for fossils // For older browsers

Got some ancient explorers hitching on, like granddaddy IE<9? Time for a resilient solution:

function ready(callback) { if (document.readyState === 'complete' || document.readyState === 'interactive') { // setTimeout fights procrastination! setTimeout(callback, 1); } else { document.addEventListener("DOMContentLoaded", callback); } }

Just serve ready() your function as a guest and it'll ensure you're covered across browsers.

Sophistication with docReady() // An alternative for advanced management

If you fancy a more controlled and sequential execution, book a suite with docReady():

docReady(() => { // Your code checks in here. });

This fellow assures the functions will march out in the order as they checked in, closely mimicking the line-up of $(document).ready().

  • Just a GitHub flyaway to jfriend00/docReady repo equips you with the most recent version with an iron-clad browser compatibility.
  • Steer clear of global namespace pollution, thanks to an Immediately Invoked Function Expression at work.
  • The function's got your back with fallbacks for legacy browsers, inclusively an IE-specific document.attachEvent('onreadystatechange', fn).

All assets onboard // Image and stylesheet readiness

While DOMContentLoaded fits the bill for most, sometimes, you'd want to wait for all assets to dock. That's when you ring up window.onload:

window.onload = function() { // All passengers aboard - stylesheets, images et al. };

Don't forget though, window.onload waits for all your assets, even the sluggish ones.

Familiarizing with events // DOMContentLoaded vs window.onload

Sufficient differences exist between DOMContentLoaded and window.onload:

  • DOMContentLoaded fires up once the HTML document is ready for operation, making it nippier, as it doesn't idle for other resources.
  • window.onload twiddles its thumbs until the whole page is brimming with all its styles, images, and whatever the document holds.

Async loading // Swifter script performance

Async scripts can jack up your performance multiple times:

<script async src="your-script.js"></script>

Being async, they don't deter your DOM from parsing and can still catch the DOM-Ready bus.

Legacy workaround // Older browser compatibility

Spiking up the compatibility thermostat for even the oldest of the lot:

// Old browsers hate to miss the fun, don't they? function r(f) { /in/.test(document.readyState) ? setTimeout(r.bind(null, f), 9) : f(); }

Ring up r(function() {}) and your code will leap to action once the DOM is ready.