Vanilla JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it
Kickstart with document.addEventListener and DOMContentLoaded to nail down a vanilla JavaScript equivalent for DOM readiness:
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:
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:
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():
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/docReadyrepo 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:
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:
- DOMContentLoadedfires up once the HTML document is ready for operation, making it nippier, as it doesn't idle for other resources.
- window.onloadtwiddles 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:
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:
Ring up r(function() {}) and your code will leap to action once the DOM is ready.
Was this article helpful?
