1、為什么需要資源預加載?
大多時候,我們的頁面並不是一次渲染完畢的,而是隨着用戶的操作,不斷修改DOM節點,如果你動態插入了一個圖片節點,那么瀏覽器要馬上發一個http請求,把圖片加載下來然后渲染在頁面上,如果用戶此時的網速不佳,那么加載這張圖片可能就會消耗幾秒鍾時間,此時頁面上什么都沒有(白屏)。最壞的情況,如果你的應用圖片很多,半天加載不出幾張圖,用戶很可能就在白屏的那幾秒走了。在游戲中更嚴重,主角的圖片如果加載不出來,讓用戶玩空氣去?
2、什么樣的項目需要預加載資源呢?
視圖/圖片較多的專題頁面,或者是需要逐幀圖片來完成的動畫效果,最好都要做預加載。
3、預加載的原理與加載進度的獲取
原理其實也相當簡單,就是維護一個資源列表,挨個去加載列表中的資源,然后在每個資源加載完成的回調函數中更新進度即可。
以圖片為例:
這個頁面加載進度條嚴格來講並不是文件加載的實時進度,因為我們只能在每個文件加載完成的時候執行回調,無法像timeline中那樣拿到文件加載的實時進度。
實際上計算方法就很簡單了,當前加載完的資源個數/資源總數*100,就是加載進度的百分比了。
$("img").size():圖片的資源總數。
預覽:
接下來有請碼碼上場:
<!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>