Vanilla JS ready() function - What is `document.documentElement.doScroll`?

Viewed 1483

I know similar questions have been asked here before, but I can't find any that asks or answers this specific question.

I want an as simple as possible pure JavaScript ready function that runs when the page has fully loaded, similar to the jQuery $(document).ready() function.

I keep finding this example:

if (document.readyState === "complete" || (document.readyState !== "loading" && !document.documentElement.doScroll)) {
    // Document already fully loaded
    ready();
} else {
    // Add event listener for DOMContentLoaded (fires when document is fully loaded)
    document.addEventListener("DOMContentLoaded", ready);
}

function ready() {
    // Handler here
}

but the websites giving this example always talk about support for older versions of IE, and I don't need that. I want to support only modern browsers (Chromium Edge, Chrome, Firefox, Opera and Safari), and hope to find a simpler solution, particularly regarding the part document.readyState !== "loading" && !document.documentElement.doScroll. I can't seem to find much information about document.documentElement.doScroll, at least not from reliable sources like MDN, so I don't know exactly what it does, or if removing this could cause the ready function to break in certain edge cases.

I guess what I'm asking is this:

Is it safe to remove document.readyState !== "loading" && !document.documentElement.doScroll from the example code, and are there even better ways to do this now when you only care about the current major browsers (listed above)?

1 Answers

It looks like doScroll is an IE thing. The readyState check is useful though, since the DOMContentLoaded event won't fire if it's already occurred. So, if you don't need IE support, I'd say you are fine removing the doScroll check, leaving you with:

if (document.readyState === "complete") {
    // Document already fully loaded
    ready();
} else {
    // Add event listener for DOMContentLoaded (fires when document is fully loaded)
    document.addEventListener("DOMContentLoaded", ready);
}

function ready() {
    // Handler here
}
Related