DEV Community

Paramanantham Harrison
Paramanantham Harrison

Posted on • Originally published at learnwithparam.com on

4

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
});
Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode

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 😎

Stay in touch!

If you enjoyed this post, you can find me on Twitter for updates, announcements, and news. 🐤

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay