一、什麼是預加載?
預加載是一種web性能優化技術,在頁面加載之前,對部分資源進行提前加載,以提供給用戶更好的體驗,提高用戶在瀏覽資源過程的流暢感。
二、預加載的實現
本次實驗依賴jq實現
首先看一下預加載實現的效果
提前對頁面中未顯示的圖片資源進行加載,當用戶在瀏覽到相應的圖片資源時直接從瀏覽器緩存中渲染在頁面上。
首先,我們使用立即執行函數,以閉包的方式,實現局部變量,避免內部變量與外部發生衝突,在內部聲明Preload函數。
這裏使用了Jq的extend函數深拷貝傳遞的對象給局部變量中
function Preload(imgs, options){
this.imgs = imgs;
this.opts = $.extend({}, Preload.DEFAULTS, options);
this._unordered();
}
定義默認的對象,each表示每加載完成一次圖片資源,就執行一次each中的函數;而all則當全部圖片資源加載完成後執行的函數
Preload.DEFAULTS = {
each: null,
all: null
}
在Preload的原型對象中創建_unordered函數,用來加載圖片資源,這裏需要注意,監聽的load和error事件是等到遍歷完成後纔會依次執行相應的回調函數
Preload.prototype._unordered = function(){
var imgs = this.imgs,
opts = this.opts,
count = 0,
len = imgs.length;
//預先對圖片進行加載存放在瀏覽器中,當頁面需要顯示該圖片時直接從緩存中獲取顯示在dom上
//過程:同步遍歷完成全部imgs中的元素並給src賦值->異步執行加載圖片
$.each(imgs, function(i, src){
if(typeof src !== 'string') return;
var imgObj = new Image();
$(imgObj).on('load error', function(e){
opts.each && opts.each(count);
if(count >= len - 1){
opts.all && opts.all();
}
count++;
});
imgObj.src = src;
});
}
將函數導出到需要使用的頁面
//導出
$.extend({
Preload: function(imgs, opts){
new Preload(imgs, opts);
}
});
html頁面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>圖片預加載之無序加載</title>
<link rel="stylesheet" type="text/css" href="index.css"/>
</head>
<body>
<div class="loading">
<span class="progress">0%</span>
</div>
<div class="box">所有圖片加載完成!!</div>
<script src="js/jquery-1.9.0.min.js"></script>
<script src="js/preload.js"></script>
<script>
var imgs = [];
var index = 0,
len = imgs.length,
$progress = $('.loading > span');
$.Preload(imgs, {
each: function(count){
$progress.html(Math.round((count + 1) / len * 100) + '%');
},
all: function(){
$('.loading').hide();
document.title = '1/' + len;
}
});
</script>
</body>
</html>
最終preload.js代碼
(function($){
function Preload(imgs, options){
this.imgs = imgs;
this.opts = $.extend({}, Preload.DEFAULTS, options);
this._unordered();
}
Preload.DEFAULTS = {
each: null,
all: null
}
Preload.prototype._unordered = function(){
var imgs = this.imgs,
opts = this.opts,
count = 0,
len = imgs.length;
//預先對圖片進行加載存放在瀏覽器中,當頁面需要顯示該圖片時直接從緩存中獲取顯示在dom上
//過程:同步遍歷完成全部imgs中的元素->異步執行加載對於圖片
$.each(imgs, function(i, src){
if(typeof src !== 'string') return;
var imgObj = new Image();
$(imgObj).on('load error', function(e){
opts.each && opts.each(count);
if(count >= len - 1){
opts.all && opts.all();
}
count++;
});
imgObj.src = src;
});
}
$.extend({
Preload: function(imgs, opts){
new Preload(imgs, opts);
}
});
})(jQuery)
(本文純屬個人學習筆記,如有不足請留言!)