What Is The Vanilla JavaScript Equivalent Of Jquery’s $.ready() Function To Call A Function When The Page/dom Is Ready For It?

In vanilla JavaScript, you can use the DOMContentLoaded event to achieve the equivalent of jQuery’s $.ready() function. Here’s an example of how to call a function when the page/DOM is ready:

document.addEventListener("DOMContentLoaded", function(){
  // Your code here
  myFunction();
});

function myFunction() {
  // Your logic here
}

In the above example, the DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. The callback function inside addEventListener will be executed when this event occurs, allowing you to call your desired function.

Note: If you want to support older browsers, you can also use window.onload event instead of DOMContentLoaded. However, DOMContentLoaded is preferred as it fires earlier than window.onload and allows for a faster execution of your code.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!