56

I want to show a running progress bar while my page is loading like here, in my page. I used a simple loading image in my example, but I want to convert it in a running progress bar. Here is my code:

$(window).load(function() {
    alert("hi");
    $('#loading').hide();
});
#loading {
    width: 100%;
    height: 100%;
    top: 0px;
    left: 0px;
    position: fixed;
    display: block;
    opacity: 0.7;
    background-color: #fff;
    z-index: 99;
    text-align: center;
}

#loading-image {
    position: absolute;
    top: 100px;
    left: 240px;
    z-index: 100;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<div id="loading">
    <img id="loading-image" src="http://cdn.nirmaltv.com/images/generatorphp-thumb.gif" alt="Loading..." />
</div>
<div id="txt">
    <h2>Let AJAX change this text</h2>
</div>
<button>Change Content</button>

Here is a JSFiddle

TylerH
  • 20,799
  • 66
  • 75
  • 101
amit gupta
  • 1,282
  • 2
  • 20
  • 36
  • 4
    What makes your site being e.g 50% loaded? – A. Wolff Sep 24 '13 at 12:45
  • this is just an example , i want to show a progress bar starting from 1% as page start loading and went up to 100% when loading is done . – amit gupta Sep 24 '13 at 12:49
  • 4
    Check out [pace.js](http://github.hubspot.com/pace/docs/welcome/) – Mottie Nov 20 '13 at 15:16
  • 1
    Agree with @Mottie - I use http://github.hubspot.com/pace/docs/welcome/ for my projects too. It's a really nice plugin and it's automatic too, which means all you have to do is include the script. – TheCarver Oct 03 '14 at 07:39

5 Answers5

16

I have copied the relevant code below from This page. Hope this might help you.

$.ajax({
  xhr: function() {
    var xhr = new window.XMLHttpRequest();
    //Upload progress
    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with upload progress
        console.log(percentComplete);
      }
    }, false);
    //Download progress
    xhr.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
        console.log(percentComplete);
      }
    }, false);
    return xhr;
  },
  type: 'POST',
  url: "/",
  data: {},
  success: function(data) {
    //Do something success-ish
  }
});
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Tapas Pal
  • 7,073
  • 8
  • 39
  • 86
  • 5
    The OP asked for a page loading progress bar. You provided an a way to determine upload progress. – Ray Nicholus Sep 24 '13 at 14:02
  • 5
    +1 You answered the hardest part of this question--determining a percent of progress. The "easy" part (the actual progress bar) could be answered many ways, including a jQueryUI progress bar: http://jqueryui.com/progressbar/ – markE Sep 24 '13 at 16:14
  • 8
    This doesn't answer the question in any way. The OP is looking for a progress bar that display the page load progress. This answer deals with upload progress. Upload != download. – Ray Nicholus Sep 24 '13 at 17:02
  • 11
    Can't you guys read? It has progress updating for BOTH upload AND download. – Daniel Tonon Jul 28 '15 at 05:34
11

It’s a chicken-and-egg problem. You won’t be able to do it because you need to load the assets to display the progress bar widget, by which time your page will be either fully or partially downloaded. Also, you need to know the total size of the page prior to the user requesting in order to calculate a percentage.

It’s more hassle than it’s worth.

Martin Bean
  • 38,379
  • 25
  • 128
  • 201
  • 7
    I am not the downvoter, but look at my scenario; `index.html` is first sent to client with jQuery already in it, inline - on document ready `$(function() { /* here */ })` I want to grab a huge `.js` file which is around 1MB, thus making sense showing the user a progress bar! – Renato Gama May 28 '14 at 00:07
  • Loading an asset on demand is not the same as loading a web page, comprising of multiple sources (images, style sheets, JavaScript files etc). You could implement a progress bar for loading a single file on demand, but not for a basic HTTP request for a web page. – Martin Bean Sep 17 '14 at 10:23
  • While it may be more hassle than it's worth, I wouldn't say it can't be done, since it obviously HAS been done (eg youtube and more and more others). – UяošKoт Jul 10 '15 at 11:01
  • 1
    @UяošKoт It can be emulated, yes. But you can’t tell how big a page is until you’ve _actually_ downloaded that page! – Martin Bean Jul 10 '15 at 13:54
  • 3
    This is the answer that you rarely see around the web, there is not much you can do to measure the webpage overall size over http, and trying to make it real is just inefficient, most developers just create the illusion of loading (by measuring how on average their pages take to load, and make the bar stop short of 100% until it fully loads). This needs to be discussed more openly on the web. – Ayyash Jan 02 '18 at 06:15
  • 1 MB is nothing unless you live in .. well u know what I mean – Martin Zvarík Jan 03 '18 at 16:36
  • @MartinBean: It's been six years since your answer. Do you have a different answer now? I'm asking because I've always wondered how developer calculate loading progress because like you said, you can't tell how big a page is until it has been downloaded. – bytrangle Sep 10 '21 at 04:43
  • 1
    @bytrangle It’ll still be difficult to do accurately. Calculating progress is one of those things that’s more difficult than it looks. A response can indicate how many bytes a HTML response is going to be, but that number won’t include the size of any included assets on that page such as images, style sheets, JavaScript files, etc which will be separate HTTP requests. – Martin Bean Sep 10 '21 at 09:04
9

Simple Steps, follow them and i guess it will solve your problem

Include these Css in your page,

.progress {
      position: relative;
      height: 2px;
      display: block;
      width: 100%;
      background-color: white;
      border-radius: 2px;
      background-clip: padding-box;
      /*margin: 0.5rem 0 1rem 0;*/
      overflow: hidden;

    }
    .progress .indeterminate {
background-color:black; }
    .progress .indeterminate:before {
      content: '';
      position: absolute;
      background-color: #2C67B1;
      top: 0;
      left: 0;
      bottom: 0;
      will-change: left, right;
      -webkit-animation: indeterminate 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
              animation: indeterminate 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite; }
    .progress .indeterminate:after {
      content: '';
      position: absolute;
      background-color: #2C67B1;
      top: 0;
      left: 0;
      bottom: 0;
      will-change: left, right;
      -webkit-animation: indeterminate-short 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) infinite;
              animation: indeterminate-short 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) infinite;
      -webkit-animation-delay: 1.15s;
              animation-delay: 1.15s; }

    @-webkit-keyframes indeterminate {
      0% {
        left: -35%;
        right: 100%; }
      60% {
        left: 100%;
        right: -90%; }
      100% {
        left: 100%;
        right: -90%; } }
    @keyframes indeterminate {
      0% {
        left: -35%;
        right: 100%; }
      60% {
        left: 100%;
        right: -90%; }
      100% {
        left: 100%;
        right: -90%; } }
    @-webkit-keyframes indeterminate-short {
      0% {
        left: -200%;
        right: 100%; }
      60% {
        left: 107%;
        right: -8%; }
      100% {
        left: 107%;
        right: -8%; } }
    @keyframes indeterminate-short {
      0% {
        left: -200%;
        right: 100%; }
      60% {
        left: 107%;
        right: -8%; }
      100% {
        left: 107%;
        right: -8%; } }

Then include the progress bar your body tag,

<div class="progress" id="PreLoaderBar">
        <div class="indeterminate"></div>
    </div>

then it will start as your page loads, and now what you have to do is just hide this when the page loads,or set the visibility to none, or hidden, using javascript,

document.onreadystatechange = function () {
            if (document.readyState === "complete") {
                console.log(document.readyState);
                document.getElementById("PreLoaderBar").style.display = "none";
            }
        }

Let me Know if you face any problems and also, you can add any type of progress bar you can easily find them, for this example i have used a indeterminate progress bar.

Omkar Dixit
  • 746
  • 1
  • 9
  • 19
4

In this sample, I created a JavaScript progress bar (with percentage display), you can control it and hide it with JavaScript.

In this sample, the progress bar advances every 100ms. You can see it in JSFiddle

var elapsedTime = 0;
var interval = setInterval(function() {
  timer()
}, 100);

function progressbar(percent) {
  document.getElementById("prgsbarcolor").style.width = percent + '%';
  document.getElementById("prgsbartext").innerHTML = percent + '%';
}

function timer() {
  if (elapsedTime > 100) {
    document.getElementById("prgsbartext").style.color = "#FFF";
    document.getElementById("prgsbartext").innerHTML = "Completed.";
    if (elapsedTime >= 107) {
      clearInterval(interval);
      history.go(-1);
    }
  } else {
    progressbar(elapsedTime);
  }
  elapsedTime++;
}
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
M-Razavi
  • 3,327
  • 2
  • 34
  • 46
3

Take a look here.

It definitely solves your problem for complete tutorial here is the link

DEMO

document.onreadystatechange = function(e) {
  if (document.readyState == "interactive") {
    var all = document.getElementsByTagName("*");
    for (var i = 0, max = all.length; i < max; i++) {
      set_ele(all[i]);
    }
  }
}

function check_element(ele) {
  var all = document.getElementsByTagName("*");
  var totalele = all.length;
  var per_inc = 100 / all.length;

  if ($(ele).on()) {
    var prog_width = per_inc + Number(document.getElementById("progress_width").value);
    document.getElementById("progress_width").value = prog_width;
    $("#bar1").animate({
      width: prog_width + "%"
    }, 10, function() {
      if (document.getElementById("bar1").style.width == "100%") {
        $(".progress").fadeOut("slow");
      }
    });
  } else {
    set_ele(ele);
  }
}

function set_ele(set_element) {
  check_element(set_element);
}
body
{
  margin:0px; auto;
  padding:0px;
  font-family:helvetica;
}
.progress 
{
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background-color: #F2F2F2;
}
.bar 
{ 
  background-color: #819FF7; 
  width:0%; 
  height:5px; 
  border-radius: 3px;
}
.percent 
{ 
  position:absolute; 
  display:inline-block; 
  top:3px; 
  left:48%; 
}
#wrapper
{
  width:995px;
  padding:0px;
  margin:0px auto;
  font-family:helvetica;
  text-align:center;
}
h1
{
  text-align:center;
  font-size:35px;
  margin-top:60px;
  color:#A9BCF5;
}
h1 p
{
  text-align:center;
  margin:0px;
  font-size:18px;
  text-decoration:underline;
  color:grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='progress' id="progress_div">
   <div class='bar' id='bar1'></div>
   <div class='percent' id='percent1'></div>
</div>

<div id="wrapper">
   <div id="content">
     <h1>Display Progress Bar While Page Loads Using jQuery<p>TalkersCode.com</p></h1>
   </div>
</div>

<input type="hidden" id="progress_width" value="0">
MaxiGui
  • 6,190
  • 4
  • 16
  • 33
naresh
  • 41
  • 1