show loading icon until the page is load?

前端 未结 7 1340
不知归路
不知归路 2020-11-29 19:42

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?

7条回答
  •  长情又很酷
    2020-11-29 20:27

    HTML

    
        
    jlkjjlkjlkjlkjlklk

    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/

提交回复
热议问题