javascripthtmldomcontentloaded

Waiting with page load until method finished


The Javascript of my webpage is executing the code shown below when a webpage is loading. The call to get can take a couple of seconds, thus I would like to wait with loading the page until the call is finished.

Is it possible to postpone the loading of the page until the call to get finished? Or even a better way would be to show some spinning wheel (instead of a white page), so that the user is aware that some process is going on. Is this possible?

document.addEventListener("DOMContentLoaded", function(){
    if (!sessionStorage.getItem("userID")) {
        // Get new userID
        $.get("/new_user").done(function (data) {
            sessionStorage.setItem("userID", data);
        });
    }
});

Solution

  • I'm not sure if your implementation with the event listener "DOMContentLoaded" is right, I think we are missing some context here and you may be able to check session storage before this, but I will assume that part is correct and address your question about a loading spinner.

    Also I wont go into detail about how to make a load spinner as there are a lot of examples out there.. but as far as having your page be a load spinner while your ajax call is running I would make the function async and set the html of the page to the loading spinner right before the call, and then after you await the call, set the data and then set the html to what you want it to be after it's done loading

    document.addEventListener('DOMContentLoaded', async (event) => {
            if (!sessionStorage.getItem("userID")) {
                document.getElementById('container').innerHTML = '<div>loadspinnerhtml</div>';
                var data = await $.get("/new_user")
                sessionStorage.setItem("userID", data);
                document.getElementById('container').innerHTML = '<div>theloadedhtml</div>'
            }
      });