Testing

webTiger Logo Wide

Plain JavaScript Equivalent of jQuery’s Document.Ready

JavaScript Logo

The following method is a plain JavaScript function that is approximately equivalent to jQuery’s $(document).ready function, but can be used without the overhead of loading the entire jQuery library if you don’t need it.

function onDocumentReady(callback) {
    var hasRun = false;
    var registered = false;

    if (document.addEventListener) {
        // Mozilla, Opera, Edge, and WebKit-based browsers should support this.
        document.addEventListener("DOMContentLoaded", function () {
            document.removeEventListener("DOMContentLoaded", arguments.callee, false);
            callback();
            hasRun = true;
        }, false);
        registered = true;

    } else if (document.attachEvent) {
        // Probably running in IE, so use document.readystate.
        document.attachEvent("onreadystatechange", function () {
            if (document.readyState === "complete") {
                document.detachEvent("onreadystatechange", arguments.callee);
                callback();
                hasRun = true;
            }
        });
        registered = true;
    }

    if (!registered) {
        // Fall back to window.onload that should always work.
        window.onload = function () {
            if (!hasRun) callback();
            hasRun = true;
        };
    }
}Code language: JavaScript (javascript)