Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a loading bar before the entire page is loaded

I would like to display a loading bar before the entire page is loaded. For now, I'm just using a small delay:

$(document).ready(function(){     $('#page').fadeIn(2000); }); 

The page already uses jQuery.

Note: I have tried this, but it didn't work for me: loading bar while the script runs

I also tried other solutions. In most cases, the page loads as usual, or the page won't load/display at all.

like image 793
Key-Six Avatar asked Jun 17 '12 16:06

Key-Six


People also ask

How do I show page loading Div until the page has finished?

Step 1: Add a background with a spinner gif on top of the page, then remove them when everything is loaded. Step 2: Add a little script right after the opening body tag to start displaying the load/splash screen.


1 Answers

Use a div #overlay with your loading info / .gif that will cover all your page:

<div id="overlay">      <img src="loading.gif" alt="Loading" />      Loading... </div> 

jQuery:

$(window).load(function(){    // PAGE IS FULLY LOADED      // FADE OUT YOUR OVERLAYING DIV    $('#overlay').fadeOut(); }); 

Here's an example with a Loading bar:

jsBin demo

;(function(){   function id(v){ return document.getElementById(v); }   function loadbar() {     var ovrl = id("overlay"),         prog = id("progress"),         stat = id("progstat"),         img = document.images,         c = 0,         tot = img.length;     if(tot == 0) return doneLoading();      function imgLoaded(){       c += 1;       var perc = ((100/tot*c) << 0) +"%";       prog.style.width = perc;       stat.innerHTML = "Loading "+ perc;       if(c===tot) return doneLoading();     }     function doneLoading(){       ovrl.style.opacity = 0;       setTimeout(function(){          ovrl.style.display = "none";       }, 1200);     }     for(var i=0; i<tot; i++) {       var tImg     = new Image();       tImg.onload  = imgLoaded;       tImg.onerror = imgLoaded;       tImg.src     = img[i].src;     }       }   document.addEventListener('DOMContentLoaded', loadbar, false); }());
*{margin:0;} body{ font: 200 16px/1 sans-serif; } img{ width:32.2%; }  #overlay{   position:fixed;   z-index:99999;   top:0;   left:0;   bottom:0;   right:0;   background:rgba(0,0,0,0.9);   transition: 1s 0.4s; } #progress{   height:1px;   background:#fff;   position:absolute;   width:0;                /* will be increased by JS */   top:50%; } #progstat{   font-size:0.7em;   letter-spacing: 3px;   position:absolute;   top:50%;   margin-top:-40px;   width:100%;   text-align:center;   color:#fff; }
<div id="overlay">   <div id="progstat"></div>   <div id="progress"></div> </div>  <div id="container">   <img src="http://placehold.it/3000x3000/cf5"> </div>
like image 168
Roko C. Buljan Avatar answered Oct 12 '22 22:10

Roko C. Buljan