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. 🐤

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more