• Skip to main content
  • Skip to primary sidebar

Technical Notes Of
Ehi Kioya

Technical Notes Of Ehi Kioya

  • Forums
  • About
  • Contact
MENUMENU
  • Blog Home
  • AWS, Azure, Cloud
  • Backend (Server-Side)
  • Frontend (Client-Side)
  • SharePoint
  • Tools & Resources
    • CM/IN Ruler
    • URL Decoder
    • Text Hasher
    • Word Count
    • IP Lookup
  • Linux & Servers
  • Zero Code Tech
  • WordPress
  • Musings
  • More
    Categories
    • Cloud
    • Server-Side
    • Front-End
    • SharePoint
    • Tools
    • Linux
    • Zero Code
    • WordPress
    • Musings
Home » Frontend (Client-Side) » Pure JavaScript Alternatives To jQuery’s ready() Function

Pure JavaScript Alternatives To jQuery’s ready() Function

October 19, 2019 by Ehi Kioya Leave a Comment

Saving this here for future reference.

If you’re reading this, my guess is that you’re probably already familiar with jQuery’s awesome…

$('document').ready(function(){});

…for executing a function only after page load is complete.

But what if you’re working with plain old JavaScript and are either not allowed to, or just don’t want to use jQuery or any other JS library? If you have some function you want to execute only after the page has loaded and is ready to handle it, how do you ensure that the page has actually completely loaded?

Naturally, the fastest and purest approach would be to put the JavaScript code at the bottom of the HTML body tag (after the rest of the DOM has been processed). But assuming that’s just not possible for some reason, try one of the following 3 pure JavaScript alternatives to jQuery’s .ready() function:

Method 1: Great For Modern Browsers. Won’t Work For IE8 And Below.

Create this function:

function ehiPureJSReady(fn) {
    
	// Check if DOM is available yet
    if (document.readyState === "interactive"
		|| document.readyState === "complete") {
        setTimeout(fn, 1);
    }
	else {
		// DOMContentLoaded works on modern browsers
		// But not on old ones like IE8 and below
        document.addEventListener("DOMContentLoaded", fn);
    }

}

And Use It Like This:

ehiPureJSReady(function() {
    // The DOM is loaded.
    // You can now add your code to manipulate it here.
});

The only 5 possible values of the readyState property (used in the above code) are: uninitialized, loading, loaded, interactive, and complete.

Method 2: Works Across All Browsers. But Feels A Little “Hacky”.

Create this function:

function ehiPureJSReady(fn) {
	/(?:loading|uninitialized)/.test(document.readyState) ? setTimeout('ehiPureJSReady(' + fn + ')',9) : fn();
}

And Use It Like This:

ehiPureJSReady(function(){
    // The DOM is loaded.
    // You can now add your code to manipulate it here.
});

What we’re doing here is that like in Method 1, we’re checking the readyState property of document. But this time, if it contains the string loading or uninitialized, we set a timeout and check again.

We keep doing this until readyState is NEITHER loading nor uninitialized. Then we execute the passed function.

Method 3: Works Across All Browsers. More Robust.

(function(funcName, baseObj) {
    "use strict";
    funcName = funcName || "ehiPureJSReady";
    baseObj = baseObj || window;
    var ehiReadyList = [];
    var isReadyFired = false;
    var isReadyEventHandlersInstalled = false;
    
    function ready() {
        if (!isReadyFired) {
            isReadyFired = true;
            for (var i = 0; i < ehiReadyList.length; i++) {
                ehiReadyList[i].fn.call(window, ehiReadyList[i].ctx);
            }
            ehiReadyList = [];
        }
    }
    
    function readyStateChange() {
        if ( document.readyState === "complete" ) {
            ready();
        }
    }
	
    baseObj[funcName] = function(callback, context) {
        if (typeof callback !== "function") {
            throw new TypeError("callback for ehiPureJSReady(fn) must be a function");
        }
		
        if (isReadyFired) {
            setTimeout(function() {callback(context);}, 1);
            return;
        }
		else {
            ehiReadyList.push({fn: callback, ctx: context});
        }
		
        if (document.readyState === "complete" || (!document.attachEvent && document.readyState === "interactive")) {
            setTimeout(ready, 1);
        }
		else if (!isReadyEventHandlersInstalled) {
            if (document.addEventListener) {
                document.addEventListener("DOMContentLoaded", ready, false);
                window.addEventListener("load", ready, false);
            }
			else {
                document.attachEvent("onreadystatechange", readyStateChange);
                window.attachEvent("onload", ready);
            }
            isReadyEventHandlersInstalled = true;
        }
    }
})("ehiPureJSReady", window);

You can use it in a number of different ways:

// Pass a named function to it
ehiPureJSReady(fn);
// Pass an anonymous function
ehiPureJSReady(function() {
    // The DOM is loaded.
    // You can now add your code to manipulate it here.
});
// Pass a named function and a context. The context becomes the first argument of the function.
ehiPureJSReady(fn, context);
// Pass an anonymous function and a context
ehiPureJSReady(function(ctx) {
    // The DOM is loaded.
    // You can now add your code to manipulate it here.
}, context);

For more information on Method 3 above, see here.

Have you used any of the above pure JavaScript alternatives to jQuery’s .ready() function? Please share your comments below.

Found this article valuable? Want to show your appreciation? Here are some options:

  1. Spread the word! Use these buttons to share this link on your favorite social media sites.
  2. Help me share this on . . .

    • Facebook
    • Twitter
    • LinkedIn
    • Reddit
    • Tumblr
    • Pinterest
    • Pocket
    • Telegram
    • WhatsApp
    • Skype
  3. Sign up to join my audience and receive email notifications when I publish new content.
  4. Contribute by adding a comment using the comments section below.
  5. Follow me on Twitter, LinkedIn, and Facebook.

Related

Filed Under: Frontend (Client-Side), JavaScript, Programming Tagged With: JavaScript, jQuery, Ready Function

About Ehi Kioya

I am a Toronto-based Software Engineer. I run this website as part hobby and part business.

To share your thoughts or get help with any of my posts, please drop a comment at the appropriate link.

You can contact me using the form on this page. I'm also on Twitter, LinkedIn, and Facebook.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

25,820
Followers
Follow
30,000
Connections
Connect
14,616
Page Fans
Like

POPULAR   FORUM   TOPICS

  • How to find the title of a song without knowing the lyrics
  • Welcome Message
  • How To Change Or Remove The WordPress Login Error Message
  • The Art of Exploratory Data Analysis (Part 1)
  • Replacing The Default SQLite Database With PostgreSQL In Django
  • How to Implement Local SEO On Your Business Website And Drive Traffic
  • Getting Started with SQL: A Beginners Guide to Databases
  • How To Create Tooltips Using CSS3
  • How To Use A Custom Bootstrap Template With Laravel
  • SEO Basics – Crawling, Indexing And Ranking
  • Recently   Popular   Posts   &   Pages
  • Actual Size Online Ruler Actual Size Online Ruler
    I created this page to measure your screen resolution and produce an online ruler of actual size. It's powered with JavaScript and HTML5.
  • Allowing Multiple RDP Sessions In Windows 10 Using The RDP Wrapper Library Allowing Multiple RDP Sessions In Windows 10 Using The RDP Wrapper Library
    This article explains how to bypass the single user remote desktop connection restriction on Windows 10 by using the RDP wrapper library.
  • WordPress Password Hash Generator WordPress Password Hash Generator
    With this WordPress Password Hash Generator, you can convert a password to its hash, and then set a new password directly in the database.
  • Forums
  • About
  • Contact

© 2021   ·   Ehi Kioya   ·   All Rights Reserved
Privacy Policy