/** * 鍥剧墖棰勫姞杞芥彃浠禤reload * * @param array imgs 棰勫姞杞界殑鍥剧墖鍦板潃鏁扮粍鍒楄〃 * @param Object options 閰嶇疆鍙傛暟 */ (function ($) { function Preload(imgs, options) { this.imgs = (typeof imgs === 'string') ? [imgs] : imgs; this.options = { order: false, //榛樿鍊糵alse,浠h〃鏃犲簭鍔犺浇 minTimer: 0, //瀹屾垚鍔犺浇鐨勬渶灏戞椂闂达紝鍗曚綅ms,榛樿涓?锛屼竴鑸睍绀虹被鍨嬬殑loading鍔ㄧ敾浼氶渶瑕佽缃 each: null, //鍗曞紶鍥剧墖鍔犺浇瀹屾墽琛岀殑鏂规硶,涓€鑸槸淇敼杩涘害鐘舵€ end: null //鎵€鏈夊浘鐗囧姞杞藉畬鎵ц鐨勬柟娉曪紝涓€鑸槸闅愯棌loading椤 }; this.timer = Date.now(); this.init(options); }; //鎻掍欢鍒濆鍖 Preload.prototype.init = function (options) { //閰嶇疆鍙傛暟鍚堝苟 this.options = $.extend(this.options, options); if (this.options.order) { this.ordered(); //鏈夊簭鍔犺浇 } else { this.unordered(); //鏃犲簭鍔犺浇 } }; // 鏈夊簭鍔犺浇 Preload.prototype.ordered = function () { var that = this, imgs = this.imgs, len = imgs.length, count = 0, options = this.options; load(); function load() { var img = new Image(); $(img).on('load error', function () { options.each && options.each(count); if (count >= len-1) { //鎵€鏈夊浘鐗囧姞杞藉畬姣?妫€鏌ユ槸鍚︽弧瓒虫渶灏弆oading鏃堕棿 var timerCount = Date.now() - that.timer; if (timerCount < options.minTimer) { console.log("111") var timeout = options.minTimer - timerCount; setTimeout(function () { options.end && options.end(); }, timeout); }else{ options.end && options.end(); } } else { load(); } count++ }); // onload鍑芥暟瑕佸啓鍦ㄦ敼鍙榮rc鍓?杩欐牱纭繚浜唎nload鍑芥暟涓€瀹氫細琚皟鐢 img.src = imgs[count]; } }; // 鏃犲簭鍔犺浇 Preload.prototype.unordered = function () { var that = this, imgs = this.imgs, len = imgs.length, count = 0, options = this.options; for (var i = 0; i < len; i++) { var img = new Image(); $(img).on('load error', function () { options.each && options.each(count); if (count >= len-1) { //鎵€鏈夊浘鐗囧姞杞藉畬姣?妫€鏌ユ槸鍚︽弧瓒虫渶灏弆oading鏃堕棿 var timerCount = Date.now() - that.timer; if (timerCount < options.minTimer) { var timeout = options.minTimer - timerCount; setTimeout(function () { options.end && options.end(); }, timeout); }else{ options.end && options.end(); } } count++; }) img.src = imgs[i]; } }; //鎵╁睍鍒癹Query瀵硅薄涓 $.extend($,{ preload: function (imgs, options) { new Preload(imgs, options); } }); })(jQuery);