Implementing a Page Loading Progress Bar with JavaScript

The following code uses JavaScript to simulate a page loading progress bar: every 100 milliseconds, it increases the progress by 2% and appends || to the text box, until it approaches 100% and then redirects to the specified page.

<form name="loading">
  <p align="center">
    <font color="#ff0000" size="2" face="Arial">Loading, please wait...</font><br>
    <input type="text" name="chart" size="46" style="font-weight: bolder; color: #ff0000;">
    <br>
    <input type="text" name="percent" size="47" style="color: #ff0000;">
  </p>
</form>

<script language="JavaScript">
<!--
var bar = 0;
var line = "||";
var amount = "||";

count();

function count() {
  bar = bar + 2;
  amount = amount + line;
  document.loading.chart.value = amount;
  document.loading.percent.value = bar + "%";

  if (bar < 99) {
    setTimeout("count()", 100);
  } else {
    window.location.href = "http://www.sina.com.cn/";
  }
}
//-->
</script>

It is important to note that this is only a "simulated progress bar" and does not actually detect the loading progress of page resources. It is suitable for simple waiting prompts, or for giving users visual feedback before a redirect that takes a fixed amount of time.

To write it in a way that better matches modern browser practices, you can avoid using the font tag, document.loading, HTML comments around scripts, and the string form of setTimeout:

<form id="loading">
  <p style="text-align: center;">
    <span style="color: #ff0000; font: 12px Arial;">Loading, please wait...</span><br>
    <input id="chart" type="text" size="46" style="font-weight: bold; color: #ff0000;">
    <br>
    <input id="percent" type="text" size="47" style="color: #ff0000;">
  </p>
</form>

<script>
let bar = 0;
let amount = "||";
const line = "||";
const chart = document.getElementById("chart");
const percent = document.getElementById("percent");

function count() {
  bar += 2;
  amount += line;
  chart.value = amount;
  percent.value = `${bar}%`;

  if (bar < 99) {
    setTimeout(count, 100);
  } else {
    window.location.href = "http://www.sina.com.cn/";
  }
}

count();
</script>

If you only need a loading indicator at the top of the page, you can also use CSS to control the width of a div, which feels more natural than appending characters inside a text box.

Source:

http://blog.csdn.net/sangliu/article/details/8718685

Leave a Reply