图片预加载

 1 (function ($) {
 2     function PreLoad(imgs, options) {
 3         this.imgs = (typeof imgs == "string") ? [imgs] : imgs;
 4         this.opts = $.extend({}, PreLoad.DEFAULTS, options);
 5 
 6         this._unoredered();
 7     }
 8     PreLoad.DEFAULTS = {
 9         each: null,//每一张图片加载完成后执行
10         all: null//所有图片加载完成后执行
11     }
12     PreLoad.prototype._unoredered = function () {
13         var imgs = this.imgs,
14             opts = this.opts,
15             count = 0,
16             len = imgs.length;
17 
18         $.each(imgs, function (i, src) {
19             if (typeof src != 'string') return;
20             var imgObj = new Image();
21             $(imgObj).on("load error", function () {
22                 opts.each && opts.each();
23 
24                 if (count >= len - 1) {
25                     $('.loading').hide();//页面上添加的loading动画隐藏
26                 }
27                 count++;
28             })
29             imgObj.src = src;
30         })
31     }
32 
33     $.extend({
34         preload: function (imgs, opts) {
35             new PreLoad(imgs, opts);
36         }
37     })
38 })(jQuery)

当已知要加载图片时方能使用,提升网页的流畅性。

posted @ 2017-12-01 16:24  浮缠  阅读(270)  评论(0)    收藏  举报