大多時候,咱們的頁面並非一次渲染完畢的,而是隨着用戶的操做,不斷修改DOM節點,若是你動態插入了一個圖片節點,那麼瀏覽器要立刻發一個http請求,把圖片加載下來而後渲染在頁面上,若是用戶此時的網速不佳,那麼加載這張圖片可能就會消耗幾秒鐘時間,此時頁面上什麼都沒有(白屏)。最壞的狀況,若是你的應用圖片不少,半天加載不出幾張圖,用戶極可能就在白屏的那幾秒走了。在遊戲中更嚴重,主角的圖片若是加載不出來,讓用戶玩空氣去?javascript
二、什麼樣的項目須要預加載資源呢?css
視圖/圖片較多的專題頁面,或者是須要逐幀圖片來完成的動畫效果,最好都要作預加載。html
三、預加載的原理與加載進度的獲取java
原理其實也至關簡單,就是維護一個資源列表,挨個去加載列表中的資源,而後在每一個資源加載完成的回調函數中更新進度便可。jquery
以圖片爲例:瀏覽器
這個頁面加載進度條嚴格來說並非文件加載的實時進度,由於咱們只能在每一個文件加載完成的時候執行回調,沒法像timeline中那樣拿到文件加載的實時進度。函數
實際上計算方法就很簡單了,當前加載完的資源個數/資源總數*100,就是加載進度的百分比了。動畫
$("img").size():圖片的資源總數。url
預覽:spa
接下來有請碼碼上場:
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>移動端頁面加載進度條</title> </head> <style type="text/css"> .loading{width: 100%;height: 100%;position: fixed;top: 0;left: 0;background: #fff;z-index: 88;} .loading .pic{width: 100px;height: 100px; text-align: center; background: url('https://m-view.eol.cn/epaper_demo/images/loading.gif') no-repeat;position: absolute;top: 0;left: 0;right: 0;bottom: 0;margin: auto;background-size: 100%;} .loading .pic span{ display: block;width:100%;position: absolute;top: 10px;left: 10px;} .loading .pic {line-height: 64px;text-align: center;} .page{text-align: center;} .page h3{font-size: 50px;} </style> <body> <!-- 進度條加載 --> <div class="loading"> <div class="pic"> <span></span> <p>0%</p> </div> </div> <!-- 正式頁面 --> <div class="page"> <img src="https://www.baidu.com/img/bd_logo1.png?where=super"/> <h3>只爲成功找方法,不爲失敗找藉口!</h3> </div> <script src="http://www.eol.cn/js/common/jquery/1.12.4/jquery.min.js" charset="utf-8"></script> <script type="text/javascript"> $(function() { var img = $("img"); var num = 0; img.each(function(i) { var oImg = new Image(); oImg.onload = function() { oImg.onload = null; num++; $(".loading p").html(parseInt(num / $("img").size() * 100) + "%"); if(num >= i) { $(".loading").fadeOut(); } } oImg.src = img[i].src; }); }) </script> </body> </html>