图片预加载插件开发小记

面向对象组件开发前端进阶不可或缺的一步,复用思想也是前端模块化的重要推动力

图片预加载在大批量图片加载的同时保证用户体验方面作用明显,浅显尝试,以此为记

插件封装(preLoad.js)

(function($) {
    function PreLoad(imgs, options) {
		this.imgs = imgs;
		this.opts = $.extend({}, PreLoad.defaults, options);
		this._loadnow();
		this._addcli(imgs);
	}
	PreLoad.defaults = {
		each: null,
		all: null
	}
	PreLoad.prototype._loadnow = function() {
		var imgs = this.imgs;
		var opts = this.opts;
		var count = 0;
		var l = imgs.length;
		$.each(imgs, function(i, src) {

			var imgObj = new Image();

			$(imgObj).on("load error", function() {
				++count;
				opts.each(count);

				if(count >= l) {
					opts.all();
				}
			});

			imgObj.src = src;
		})

	}
	PreLoad.prototype._addcli = function(imgs) {
		var l = imgs.length;
		var index = 0;
		$("#prev").click(function() {
			if(index < 1) return;
			$(".box>img").attr('src', imgs[--index]);
		})
		$("#next").click(function() {
			if(index >= l - 1) return;
			$(".box>img").attr('src', imgs[++index]);

		})
	}
	$.extend({
		preload: function(imgs, options) {
			new PreLoad(imgs, options);
		}
	});
})(jQuery)
插件使用




	
		
		
		
	

	
		
上一页 下一页

0%



你可能感兴趣的:(前端模块化)