JS/CSS Loading spinner finishes before JS executes

  html, javascript

Kinda JS/dev newbie here. Having a play around with a loading spinner – this is the example I’m working from. I’ve currently got a bunch of JS calculations that are performed on a Flask/SQLite backend API. I’ll ignore the CSS as it’s likely irrelevant.

document.onreadystatechange = function() {
    if (document.readyState !== "complete") {
        document.querySelector("main").style.visibility = "hidden";
        document.querySelector("#loader").style.visibility = "visible";
    } else {
        document.querySelector("#loader").style.display = "none";
        document.querySelector("main").style.visibility = "visible";
    }
};

This in the html:

<main role="main" class="container">
    <div id="loader" class="spinner-1"></div>
    ...content here...
</main>
<script type="text/javascript" src="{{ url_for ('static', filename='scripts/main.js') }}"></script>

The issue is that the JS is still running on DOM load. So the spinner disappears and items are still being added to the DOM via JS. They appear after the spinner disappears, which negates the point of having a spinner!

I’ve tried several of these methods, but they all work the same.

I thought about having the conditional tied to one of the loading items, but that seems a bit clunky and I’d not be able to repeat the code on other pages on the site. Is there a baked in JS method for doing this properly?

Source: Ask Javascript Questions

LEAVE A COMMENT