1

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);
        });
    }
});
BlackHawk
  • 719
  • 1
  • 6
  • 18
  • We expect you to do research before asking. There are a ton of pre-loader/"loading screen" examples and tutorials available. – Ouroborus Apr 19 '22 at 16:42
  • What you're talking about is not a page loading event. Don't re-use it that way or else some future person (probably you) will think "What the heck?!?” later. Make up your own event instead, or remove the spinner imperatively once the data is loaded. – JSmart523 Apr 19 '22 at 16:42

1 Answers1

1

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>'
        }
  });
BrokenWings
  • 169
  • 12