How to execute functions when DOM is loaded without jQuery?

I’m trying to find a way to run JavaScript functions as soon as the DOM is ready, but without using jQuery. I know about window.onload and the onload attribute in the <body> tag, but I’m not sure if these are the best options.

Here’s what I’ve tried so far:

window.onload = function() {
  initializePage();
};

Or in HTML:

<body onload="initializePage()">

I’ve also considered putting a script at the end of the page:

<script>
  initializePage();
</script>

Are there any better methods that work across different browsers? I’m looking for something similar to jQuery’s .ready() function, but in vanilla JavaScript. Any suggestions would be really helpful!

The most efficient way to execute functions when the DOM is loaded without jQuery is using the ‘DOMContentLoaded’ event listener. It’s widely supported and doesn’t wait for images or stylesheets to load, unlike window.onload.

Here’s how you can implement it:

document.addEventListener(‘DOMContentLoaded’, function() {
initializePage();
});

This method is similar to jQuery’s .ready() function but in vanilla JavaScript. It’s reliable across browsers and ensures your code runs as soon as the DOM is fully loaded and parsed.

If you need to support older browsers, you might want to include a fallback:

if (document.readyState === ‘loading’) {
document.addEventListener(‘DOMContentLoaded’, initializePage);
} else {
initializePage();
}

This approach covers all bases and should work smoothly in your project.

I’ve actually faced this exact issue in a recent project. After some trial and error, I found that using the ‘DOMContentLoaded’ event listener is the most reliable method across browsers. Here’s what worked for me:

document.addEventListener(‘DOMContentLoaded’, function() {
// Your initialization code here
initializePage();
});

This approach is great because it doesn’t wait for images or other resources to load, unlike window.onload. It fires as soon as the DOM is ready, which can significantly speed up your page’s responsiveness.

One thing to watch out for: if you’re supporting really old browsers, you might need a fallback. But for modern web development, this method has served me well. It’s clean, efficient, and doesn’t require any external libraries. Just remember to keep your initialization function lightweight to maintain that quick load time!

hey grace, have you tried using document.addEventListener(‘DOMContentLoaded’, function() { // your code here })? its pretty much the vanilla js equivalent of jquery’s ready(). works great across browsers and doesnt wait for images to load like window.onload does. hope this helps!