简体   繁体   中英

Changing HTML elements through JS doesn't update immediately

On my website I have quite large 3d model files that need to be loaded and I want to show the user how many 3d objects are already loaded. I created two variables, that get incremented when an object is requested or loaded successfully. Printing this out on console works, but I want to change two HTML outputs I created like this:

Loaded objects: <output id="loaded"></output>
Requested objects: <output id="requested"></output> 

to show the current status. To update the numbers I use these commands:

function updateLoadNumbers() {
    document.getElementById("loaded").value = loadedObjects;
    document.getElementById("requested").value = requestedObjects;
}

I call this function, when a new object has been created and I call it when an object has been successfully processed. The latter happens at the end of an callback that was started by an XMLHttpRequest .

This is a shortened version of the code:

function loadFileAsText(filename, callback) {
  var req = new XMLHttpRequest();
  //setting up the request

  req.onload = function() {
    if(req.status >= 200 && req.status < 300 || req.status == 0)
      callback(req.responseText);
  };
}


//Part of the function to process a file
loadFileAsText(filename, (result) => {
    /*
    All the processing
    */

    loadedObjects++;
    updateLoadNumbers();
}

But the text only updated when the loading is done , when it is useless. How can I get the HTML to update faster?

If I got what do you want to achieve then:

first, you need correct HTML tags like this:

Loaded objects: <span id="loaded"></span>
Requested objects: <span id="requested"></span>

and just fill the textContent of each of them inside the onprogress callback which has an event that includes two information that you need here, event.loaded the bytes the browser received and event.total the total bytes set by the header. so your code might look like that:

var loadedInfo = document.getElementById("loaded");
var requestedInfo = document.getElementById("requested");

xhr.addEventListener('progress', function(event){
   loadedInfo.textContent = event.loaded;
   requestedInfo.textContent = event.total;
});

If you are not familiar with xhr requests yet I recommend you to check this: XmlHTTPRequest MDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM