Snippets Collections
(function (root, factory) {
	if (typeof define === "function" && define.amd) {
		define("onDomReady", factory(root));
	} else if (typeof exports === "object") {
		module.onDomReady = factory(root);
	} else {
		root.onDomReady = factory(root);
	}
})(this, function (root) {
    "use strict";
    
    var win = window,
        doc = win.document,
        docElem = doc.documentElement,
        
        LOAD = "load",
        FALSE = false,
        ONLOAD = "on"+LOAD,
        COMPLETE = "complete",
        READYSTATE = "readyState",
        ATTACHEVENT = "attachEvent",
        DETACHEVENT = "detachEvent",
        ADDEVENTLISTENER = "addEventListener",
        DOMCONTENTLOADED = "DOMContentLoaded",
        ONREADYSTATECHANGE = "onreadystatechange",
        REMOVEEVENTLISTENER = "removeEventListener",
        
        isEventListener = ADDEVENTLISTENER in doc,
        isDomReady = FALSE,
        domReadyCallBacks = [];
        
    var exports = function (func) {
        function defer (func, wait) {
            setTimeout(func, +wait >= 0 ? wait : 1);
        }
        
        function ready (func) {
            if (!isDomReady) {
                if (!doc.body) {
                    return defer(ready);
                }
                
                isDomReady = true;

                while (func = domReadyCallBacks.shift()) {
                    defer(func);
                }
            }
        }
        
        function detach() {
            if (isEventListener) {
                doc[REMOVEEVENTLISTENER](DOMCONTENTLOADED, completed, FALSE);
                win[REMOVEEVENTLISTENER](LOAD, completed, FALSE);
            } else {
                doc[DETACHEVENT](ONREADYSTATECHANGE, completed);
                win[DETACHEVENT](ONLOAD, completed);
            }
        }
        
        function completed (event) {
            if (isEventListener || event.type === LOAD || doc[READYSTATE] === COMPLETE) {
                detach();
                ready();
            }
        }
        
        if (doc[READYSTATE] === COMPLETE) {
            defer(ready);
        } else if (isEventListener) {
            doc[ADDEVENTLISTENER](DOMCONTENTLOADED, completed, FALSE);
            win[ADDEVENTLISTENER](LOAD, completed, FALSE);
        } else {
            doc[ATTACHEVENT](ONREADYSTATECHANGE, completed);
            win[ATTACHEVENT](ONLOAD, completed );
        }
        
        isDomReady ? defer(func) : domReadyCallBacks.push(func);
    };
    
    return exports;
});

// An example of the use of function onDomReady.
onDomReady(function(){
    console.log("DOM IS READY");
});
star

Thu Oct 19 2023 06:37:18 GMT+0000 (Coordinated Universal Time)

#javascript #ondomready #readystate #defer #domcontentloaded

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension