Search code examples
javascripthtmlwait

How to prevent HTML from loading until all server data is processed?


In my project, my JS receives information from server and then displays it on HTML. However, when I acess the page, the data is not fully loaded yet, so the entire HTML is loaded but the data is not. It forces me to wait X milliseconds to see the last thing to complete the page (the data).

I want to make all elements (divs, span, buttons, my data) load exactly when data's retrieved and ready to be shown. Also, I wanted to do this by displaying a simple waiting gif in order to make the user pacient about it, but I'm not sure how to do it.

window.onload = ()=>{
  var questionPlace = document.querySelector("#question-place");
  displayPrevious(data, questionPlace);
}
<head>
<script src='./scripts/index.js' type='module'></script>
</head>
<body>
    <div class="flexbox-container" id="question-place"> <!-- data here --> </div>
    <!-- buttons, divs, etc -->    
</body>


Solution

  • Rather than window.onload, use $.when($.ajax()).then():

    Option 1:
    Create every element using document.createElement:

    //window.onload = () => {
    $.when($.ajax("file.txt")).then((data, textStatus, jqXHR) => {
      var elements = [];
      elements.push(document.createElement('div'));
    });
    

    And the only element that should be in the <body> would be your gif:

    <body>
      <img src="loading.gif" alt="Loading...">
    </body>
    

    Option 2:
    Set every element to have display: none;:

    <head>
      <style>
        * {
          display: none; 
        }
      </style>
    </head>
    <body>
      <!-- other elements -->
      <img src="loading.gif" alt="Loading..." onload="(event) => event.target.style.display = 'block'">
    </body>
    

    And again wait for the call to finish and set everything to block:

    $.when($.ajax("file.txt")).then((data, textStatus, jqXHR) => {
      $("*").css("display", "block");
    });