59

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.

Key-Six
  • 2,439
  • 2
  • 26
  • 22

5 Answers5

95

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>
MaxiGui
  • 6,190
  • 4
  • 16
  • 33
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • 1
    Are you sure there is no "side effects"? I was remembering .load() wasn't waiting for some elements, like a full load of all images in the page. **Edit:** I wasn't remembering well, it shouldn't have any side effect, [here is an explanation why](http://ablogaboutcode.com/2011/06/14/how-javascript-loading-works-domcontentloaded-and-onload/) – Erdal G. Jun 21 '13 at 10:09
  • 3
    I realise that this answer is a bit old, but I was wondering if there was a solution that would degrade nicely if the user has javascript disabled? Because currently they'd just end up with a loading gif for a website. – arandompenguin Mar 06 '14 at 19:55
  • weird, question with many views but no upvotes on a useful answer – Mr. Alien Jul 21 '14 at 19:45
  • @arandompenguin if you load the image using script at the beginning that should solve your problem. – Jeff Thomas Sep 25 '14 at 17:42
  • @roko How can show the loading gif until the first page is completely loaded? I have a parallax website and I want to show loading only till my first pages have been fulyloaded. – Faizan Apr 17 '15 at 11:55
  • @Roko, deleted my last comment as my issue wasn't with the above code. It was a strange conflict with ipad's safari and a plugin I'm using that works on every other tablet but ipad. – GregT May 09 '15 at 15:45
  • is it possible to replace the images load by scripts or css files ? if i just want to make my loader for wait my home page is ready. – Thibaud Jan 01 '16 at 17:28
  • Why its perfect! I got an error when it loading in mozilla. console says TypeError: window.runnerWindow is undefined window.runnerWindow.protect.protect({ – Krish Jun 28 '16 at 06:26
  • Well, i just removed "window.runnerWindow" line and it worked, i think its a issue from jsBin. – Krish Jun 29 '16 at 07:54
  • How to make it loading more smooth? – TheCrazyProfessor Nov 28 '16 at 12:21
  • @TheCrazyProfessor you can always use jQuery's `$(prog).animate({width: perc});` – Roko C. Buljan Nov 28 '16 at 15:44
25

HTML

<div class="preload">
<img src="http://i.imgur.com/KUJoe.gif">
</div>

<div class="content">
I would like to display a loading bar before the entire page is loaded. 
</div>

JAVASCRIPT

$(function() {
    $(".preload").fadeOut(2000, function() {
        $(".content").fadeIn(1000);        
    });
});​

CSS

.content {display:none;}
.preload { 
    width:100px;
    height: 100px;
    position: fixed;
    top: 50%;
    left: 50%;
}
​

DEMO

Okan Kocyigit
  • 13,203
  • 18
  • 70
  • 129
  • Is it possible to set opacity of white background when page loading? currently it is displaying white background and loader during page loading. I want to display transparent content during loading. Please let me know. – RK Ahir Dec 03 '20 at 06:38
  • Also loader is not displaying exactly in center of page. Please help for this too. – RK Ahir Dec 03 '20 at 06:41
11

Whenever you try to load any data in this window this gif will load.

HTML

Make a Div

<div class="loader"></div>

CSS

.loader {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background: url('https://lkp.dispendik.surabaya.go.id/assets/loading.gif') 50% 50% no-repeat rgb(249,249,249);
}

jQuery

$(window).load(function() {
        $(".loader").fadeOut("slow");
});
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>

enter image description here

Rohit Suthar
  • 3,528
  • 1
  • 42
  • 48
Inamur Rahman
  • 2,913
  • 1
  • 27
  • 29
4

I've recently made a page loader in VanillaJS for a project, just wanted to share it as, all the other answers, are jQuery based. It's a plug and play, one-liner.

let settings={backgroundColor:"#2774ab",filterBrightness:2,timeOnScreen:100},u=document.querySelector("*"),s=document.createElement("style"),a=document.createElement("div"),m="http://www.w3.org/2000/svg",g=document.createElementNS(m,"svg"),c=document.createElementNS(m,"circle");document.head.appendChild(s),s.innerHTML="@keyframes swell{to{transform:rotate(360deg)}}",a.setAttribute("style","background-color:"+settings.backgroundColor+";color:"+settings.backgroundColor+";display:flex;align-items:center;justify-content:center;position:fixed;top:0;height:100vh;width:100vw;z-index:2147483647"),document.body.prepend(a),g.setAttribute("style","height:50px;filter:brightness("+settings.filterBrightness+");animation:.3s swell infinite linear"),g.setAttribute("viewBox","0 0 100 100"),a.prepend(g),c.setAttribute("cx","50"),c.setAttribute("cy","50"),c.setAttribute("r","35"),c.setAttribute("fill","none"),c.setAttribute("stroke","currentColor"),c.setAttribute("stroke-dasharray","165 57"),c.setAttribute("stroke-width","10"),g.prepend(c),u.style.pointerEvents="none",u.style.userSelect="none",u.style.cursor="wait",window.onload=(()=>{setTimeout(()=>{u.style.pointerEvents="",u.style.userSelect="",u.style.cursor="",a.remove()},settings.timeOnScreen)});

Fundamentals

  • Generate a <script> element appended to the <head> element, containing any required styling.
  • Generate a <div> element, acting as overlay, prepended to the <body> element.
  • Generate a <svg> element, acting as loader, prepended to the previously generated <div> element.
  • On window.onload self generated elements are automatically removed.

The latest version is available on my GitHub.

Demo

Settings

let settings = {
    backgroundColor: "#2774ab",
    filterBrightness: 2,
    timeOnScreen: 100
}, //...
Option Description
backgroundColor Refer to MDN Web Docs color for acceptable values. The background-color CSS property sets the background color of an element. Default to Wordpress deep blue accent #2774ab #2774ab
filterBrightness number or percentage. The brightness of the svg loader element (brightness() CSS function). A value under 100% darkens the loader, while a value over 100% brightens it. The lacuna value for interpolation is 1. Default to 2.
timeOnScreen Positive integer. The time on screen is appended to the page loading time. Default to 100 milliseconds.
amarinediary
  • 4,930
  • 4
  • 27
  • 45
0

Semantic UI might also help, with just simple one liner to show and to hide the loading icon.

Eg: <div class="ui active centered inline loader"></div>

Source: https://semantic-ui.com/elements/loader.html

Found a code sample: https://codepen.io/fujiyamayuta/pen/JBxxJO

Although, there is a small typo in the JS file of the above code sample, corrected is shown below:

// ** Loader ON
$('#dimmer').dimmer('show');

// ** Loader OFF
// $('#dimmer').dimmer('hide');