Home > OS >  Get the loading progress in JavaScript
Get the loading progress in JavaScript

Time:09-21

So I'm thinking about making a gravatar link getter and I would like to add a loading screen but I don't know how to get loading progress with JavaScript when loading HTML and CSS assets

let loadingpercent = percent();

function LoadProj()
{
  document.write("Hold On, your request is loading.<br> "   loadingpercent);
}

function percent()
{
    //Code Goes here
    return NaN;
}
<input type="button" onClick="LoadProj()" value="LoadMe">

CodePudding user response:

You can store the percent in a variable and the interval at which the progress should increment in another (in ms).

Then, in your LoadProj function, increment the percent and set the innerHTML of the body to the right value. Check if the percent is not 100. If it is not, we can use setTimeout to call LoadProj again with a delay, in our case, loadInterval. If it is, you know that it is finished loading, and you can handle it accordingly.

var percent = 0;
var loadInterval = 100;

function LoadProj() {
  percent  ;
  document.body.innerHTML = "Hold On, your request is loading. "   percent;
  if (percent != 100) {
    setTimeout(LoadProj, loadInterval)
  }else{
    //Finished loading! Your code here...
    console.log('Finished loading!')
  }
}
<input type="button" onClick="LoadProj()" value="LoadMe">

  • Related