-
大小: 2.40KB文件類型: .js金幣: 1下載: 0 次發布日期: 2021-03-17
- 語言: JavaScript
- 標簽: 預加載??
資源簡介
【實例簡介】
封裝圖片預加載功能,便于直接調用
【使用方法】
//使用方式:
// var imgs = []; //存放圖片地址的數組
// $.Load(imgs ,{
// order : 'unordered', //是否有序預加載,默認無序unordered,有序為ordered
// each : function(count){
// 每張圖片加載完成的操作
// },
// all : function(){
// 所有圖片加載完成之后的操作
// }
// })
【核心代碼】
(function ($) {
function UnorderedLoad(imgs , options){
this.imgs = (typeof imgs === 'string') ? [imgs] : imgs;
this.opts = $.extend({}, UnorderedLoad.defaults, options); //后兩個對象融合生成新的{}對象(即第三個覆蓋第二個,生成第一個對象),返回給this.opts保存
if(this.opts.order === 'ordered'){
this.ordered();
}else{
this.unordered();
}
};
UnorderedLoad.defaults = {
order : 'unordered', //是否有序預加載,默認無序
each : null, //每張圖片加載完成之后執行
all : null //所有的圖片加載完成之后執行
};
UnorderedLoad.prototype.ordered = function(){ //有序加載
var imgs = this.imgs,
opts = this.opts,
count = 0,
len = imgs.length;
function load(){
var imgObj = new Image();
$(imgObj).on('load error',function(){
opts.each && opts.each(count); //判斷方法是否存在,若存在,則執行
if(count >= len){
//所有圖片加載完成
opts.all && opts.all();
}else{
load();
}
count ;
});
imgObj.src = imgs[count];
};
load();
},
UnorderedLoad.prototype.unordered = function(){ //無序加載
var imgs = this.imgs,
opts = this.opts,
count = 0,
len = imgs.length;
$.each(imgs , function(i , src){
if(typeof src != 'string'){
return;
}
var imgObj = new Image();
$(imgObj).on('load error',function(){
opts.each && opts.each(count);
if(count >= len - 1){
opts.all && opts.all();
}
count ;
});
imgObj.src = src;
});
};
$.extend({
Load : function(imgs,opts){
new UnorderedLoad(imgs,opts);
}
});
})(jQuery);
//使用方式:
// var imgs = []; //存放圖片地址的數組
// $.Load(imgs ,{
// order : 'unordered', //是否有序預加載,默認無序unordered,有序為ordered
// each : function(count){
// 每張圖片加載完成的操作
// },
// all : function(){
// 所有圖片加載完成之后的操作
// }
// })
代碼片段和文件信息
- 上一篇:jQuery+circliful圓形百分比統計圖
- 下一篇:ztree幫助文檔
評論
共有 條評論