Explain Codes LogoExplain Codes Logo

What is the non-jQuery equivalent of '$(document).ready()'?

javascript
dom
utility-functions
promises
Alex KataevbyAlex Kataev·Oct 31, 2024
TLDR

To mimic $(document).ready() in jQuery using vanilla JavaScript, use the DOMContentLoaded event to ensure code runs after the DOM is fully parsed yet prior to loading images and external resources.

document.addEventListener('DOMContentLoaded', function() { // Initialize your magic here... });

Handling older browsers

For vintage browsers (nostalgia alert), especially IE8 and older, you may have to be more creative. Use the readyState property and check when it's 'interactive', signifying the DOM is fully parsed.

document.onreadystatechange = function () { if (document.readyState === 'interactive') { // Rock 'n roll time... } };

Be sure to delve into MDN documentation to master the nuances of different readyState values.

Versatile utility duo

Let's amp up your arsenal with utility functions that add flexibility and control, handling both DOM readiness and window loading (including all your images, scripts, plugins). Consider them your trusty cavalry.

function domReady(callback) { if (document.readyState === 'interactive' || document.readyState === 'complete') { callback(); } else { document.addEventListener('DOMContentLoaded', callback); } } function windowReady(callback) { if (document.readyState === 'complete') { callback(); } else { window.addEventListener('load', callback); } } domReady(() => { // DOM's ready, let's party... }); windowReady(() => { // Everything's loaded, fireworks can start! });

Promises – The next level

To level up, let's make things smoother with Promises, thus making your logic more reliable and easy to manage.

const domReadyPromise = new Promise((resolve) => { domReady(resolve); }); domReadyPromise.then(() => { // Code ready to shoot after the DOM is ready });

Ditch jQuery – stay lean

Opt for lightweight and efficient alternatives at 'http://youmightnotneedjquery.com/#ready' to minimize dependence on jQuery. Stay lean, stay fast!

TypeScript assures type safety

For those using TypeScript, consider integrating it to add type safety to your utility helper functions to prevent accidentally passing non-executable arguments:

function domReady(callback: () => void): void { // Previous implementation }

Don't forget to sweep up after the party by removing event listeners once they've done their job { once: true }, to avoid lingering memory guests.

document.addEventListener('DOMContentLoaded', function() { // Code here... }, { once: true });

Mind the loading time

Remember, unlike DOMContentLoaded, window.onload chivalrously waits for every resource (including your images and iframes) to load. With separate listeners, you can manage sub-resource loading with finesse.

Practice with examples

Here are some examples, seasoned with some humor, for you to try your hands on. Remember, practice takes you from noobville to mastering .readyState-fu faster than you can say DOMContentLoaded.

// For the coolest browsers if (document.readyState !== 'loading') { // Run this if DOM's already chilling } else { document.addEventListener('DOMContentLoaded', function() { // The DOM's chilling now. Run your code }); } // For those retro, golden-oldie IE8 browsers document.onreadystatechange = function () { if (document.readyState === 'complete') { // All aboard the nostalgia train. Run your vintage code! } };

Check out libraries such as domReady.js for hassle-free, ready-to-rock solutions.