JavaScript - Loading spinner while the page loads

Viewed 147

I have a PHP page that uses data through an API. The data takes around 5 seconds to load. This is a 'long time' and people assume that the page stopped load. I would like a loading image to be displayed from before the page is loaded until it finishes loading.

I tried this code. Javascript:

<script type="text/javascript">
    document.onreadystatechange = function () {
        var state = document.readyState;
        if (state === 'interactive') {
            document.querySelector('.loadingGif').style.display = "block"; //don't touch
        } else if (state === 'complete') {
            setTimeout(function () {
                document.querySelector('.loadingGif').style.display = "none";//don't touch
                document.querySelector('.form-group').style.display = "visible";
            }, 2000);
        }
    };
</script>

My HTML

<div class="loadingGif" style="display:none">
    <img src="https://mir-s3-cdn-cf.behance.net/project_modules/disp/35771931234507.564a1d2403b3a.gif?token='<?php random_int(1, 1000000); ?>'">

</div>

Everything seems to work - except that the loading div seems to appear for 2 seconds before the page is fully loaded. E.g. the API starts fetching data, the loading div appears and then it dissappers.

I would like it to have the loading div display before the page starts loading while fetching the data in the background and stop after the site loads.

0 Answers
Related