Sky Sky - 3 months ago 9
CSS Question

show loading icon until the page is load?

I wanted to show a loading icon to users until the page elements are fully loaded. How can i do that with javascript and i want to do it with javascript not jquery.

https://www.googlesciencefair.com/en/ Here is a link how google does it
How can i do this?
triggering some function on onload event or something like this .. i know it will be done somewhat like this or any other ways to do it?
Or there is some event for it?

UPDATE
I did something using display property i hide the body element but and onload of body tag i change its property but where to put the loading icon and add more interactivity.

Answer

HTML

<body>
    <div id="load"></div>
    <div id="contents">
          jlkjjlkjlkjlkjlklk
    </div>
</body>

JS

document.onreadystatechange = function () {
  var state = document.readyState
  if (state == 'interactive') {
       document.getElementById('contents').style.visibility="hidden";
  } else if (state == 'complete') {
      setTimeout(function(){
         document.getElementById('interactive');
         document.getElementById('load').style.visibility="hidden";
         document.getElementById('contents').style.visibility="visible";
      },1000);
  }
}

CSS

#load{
    width:100%;
    height:100%;
    position:fixed;
    z-index:9999;
    background:url("https://www.creditmutuel.fr/cmne/fr/banques/webservices/nswr/images/loading.gif") no-repeat center center rgba(0,0,0,0.25)
}

Note:
you wont see any loading gif if your page is loaded fast, so use this code on a page with high loading time, and i also recommend to put your js on the bottom of the page.

DEMO

http://jsfiddle.net/6AcAr/ - with timeout(only for demo)
http://jsfiddle.net/47PkH/ - no timeout(use this for actual page)

update

http://jsfiddle.net/d9ngT/