Vanilla JS equivalent for jQuery Ready

jQuery has solved the problems of neutralizing side effects in JS rendering across different browsers for last decade. Now web browsers and rendering engines are much more smarter and increasingly support standard javascript API.

Document ready function is widely used feature from jQuery. With growing trends in modern web development and much better browser support for vanilla JS API's, We can replace or reduce jQuery dependency easily.

// Longer version in jQuery
$(document).ready(function () {
  // DOM events and DOM manipulations
})
// Shorter version in jQuery
$(function () {
  // DOM events and DOM manipulations
})

Lets see the example of ready function in vanilla JS

function ready(callbackFunc) {
  if (document.readyState !== 'loading') {
    // Document is already ready, call the callback directly
    callbackFunc()
  } else if (document.addEventListener) {
    // All modern browsers to register DOMContentLoaded
    document.addEventListener('DOMContentLoaded', callbackFunc)
  } else {
    // Old IE browsers
    document.attachEvent('onreadystatechange', function () {
      if (document.readyState === 'complete') {
        callbackFunc()
      }
    })
  }
}

ready(function () {
  // your code here
})

This snippet is supported on modern browsers and old IE browsers too. You can restrict support based on requirement.

DOMContentLoaded only waits till the DOM element gets loads, not wait for stylesheet, images and other network calls. Next time if you use jquery on a site, make sure to evaluate whether you need extra 30+ kb on page load just for basic JS operations šŸ˜Ž

šŸ”„ Limited Time Offer
Coding with AI: Learn to build a SaaS MVP in 10 days

Coding with AI: Learn to build a SaaS MVP in 10 days

Master practical AI development to build and launch your startup MVP in weeks instead of months. Learn to leverage AI tools and APIs effectively.

  • šŸŽÆ Build real MVP: AI-powered SaaS from idea to launch
  • šŸ¤– Integrate ChatGPT, Claude, and other AI APIs efficiently
  • šŸ’° Implement AI features users will pay for
  • āš”ļø AI-assisted coding patterns to ship 10x faster
  • šŸš€ Launch your product in 10 days, not 10 months