Vanilla JS equivalent for jQuery Ready

April 05, 2019 • 🍿 1 min read • Edit this post on Github

This is part 1 of 2 in my series on "You don't need jQuery"

Follow me on twitter. I share quick tips, my reading list and also about free workshop and webinars around web and mobile development everyday.

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
  } 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') {

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 😎

Wanna become a Pro Engineer!

Weekly, practical advice on how to become a better Engineer. Read by 210+ engineers, managers, and founders.


Made with ❤️ in Tallinn, Estonia

Paramanantham Harrison's DEV Profile