在开发H5项目中有时候会遇到要加载大量图片的情况,利用预加载技术可以提高用户浏览时的体验。
1)概念:
懒加载也叫延迟加载:JS图片延迟加载,延迟加载图片或符合某些条件时才加载某些图片。
预加载:提前加载图片,当用户需要查看时可直接从本地缓存中渲染。
2)区别:
两种技术的本质:两者的行为是相反的,一个是提前加载,一个是迟缓甚至不加载。懒加载对服务器前端有一定的缓解压力作用,预加载则会增加服务器前端压力。
服务器端区别:懒加载的主要目的是作为服务器前端的优化,减少请求数或延迟请求数。预加载可以说是牺牲服务器前端性能,换取更好的用户体验,这样可以使用户的操作得到最快的反映。
例子:
preload * { margin: 0; pading: 0; } a { text-decoration: none; } .box { text-align: center; } .btn { display: inline-block; height: 30px; line-height: 30px; border: 1px solid #ccc; background: #fff; padding: 0 10px; margin-right: 50px; color: #333; } .btn:hover { background: #eee; } .loading { position: fixed; top: 0; left: 0; bottom: 0; right: 0; //撑满整个屏幕 background: #eee; text-align: center; font-size: 30px; font-weight: bold; } .progress { margin-top: 300px; } 上一张 下一张
0%
插件:
; (function ($) {
function PreLoad(imgs, options) {
//保存图片到数组
this.imgs = (typeof imgs === 'string') ? [imgs] : imgs;
this.opts = $.extend(PreLoad.defaults, options);
// this._unordered();//如果只有无序预加载
if (this.opts.order === 'ordered') {
this._ordered();
} else {
this._unordered();//默认是无序预加载
}
};
PreLoad.defaults = {
order: 'unordered', //指定默认加载方式为无序
each: null, //每一张图片加载完毕后执行
all: null //所有图片加载完毕后执行
};
//有序预加载
PreLoad.prototype._ordered = function () {
var opts = this.opts,
imgs = this.imgs,
len = imgs.length,
count = 0;
load();
function load() {
var imgObj = new Image();
$(imgObj).on('load error', function () {
//相当于if(opts.each){ opts.each(); } ,如果有配置each()方法则调用,后面的all()同理
opts.each && opts.each(count);
if (count >= len) {
//所有图片加载完毕
opts.all && opts.all();
} else {
//如果没加载完,继续调用自身加载下一张
load();
}
count++;
});
imgObj.src = imgs[count];//缓存图片
};
};
//无序加载
PreLoad.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 && opts.each(count);
if (count >= len - 1) {
//判断opts.all是否存在,存在则执行
opts.all && opts.all();
}
count++;
});
imgObj.src = src;//缓存图片
});
};
//由于不用具体的对象去调用,因此用$.extend(object)挂载插件.
$.extend({
//preload为插件名
preload: function (imgs, opts) {
new PreLoad(imgs, opts);
}
});
})(jQuery);
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



