教程集 www.jiaochengji.com
教程集 >  jQuery  >  jquery 教程  >  正文 jquery 图片预加载代码一例

jquery 图片预加载代码一例

发布时间:2015-11-05   编辑:jiaochengji.com
本文分享一段实现图片预加载功能的js代码,有需要的朋友,可以学习参考下。

对于同一页面展示大量图处的情况,可以考虑实现预加载,并且动态计算宽高实现等比例缩放.
代码:

// 参数: 图片地址, 尺寸就绪事件, 完全加载事件, 加载错误事件 imgReady(imgUrl, function () { statusReady.innerHTML = '耗时 ' + (time.stop() / 1000) +' 秒. 宽度: ' + this.width + '; 高度: ' + this.height; checkboxFn(); }, function () { statusLoad.innerHTML = '耗时 ' + (time.stop() / 1000) +' 秒. 宽度: ' + this.width + '; 高度: ' + this.height; }, function () { statusLoad.innerHTML = statusReady.innerHTML = '耗时 ' + (time.stop() / 1000) +' 秒. 加载错误!'; });

函数代码:

/** * 图片头数据加载就绪事件 - 更快获取图片尺寸 * @param {String} 图片路径 * @param {Function} 尺寸就绪 * @param {Function} 加载完毕 (可选) * @param {Function} 加载错误 (可选) * @example imgReady('http://www.google.com.hk/intl/zh-CN/images/logo_cn.png', function () { alert('size ready: width=' + this.width + '; height=' + this.height); }); */ var imgReady = (function () { var list = [], intervalId = null, // 用来执行队列 tick = function () { var i = 0; for (; i < list.length; i++) { list[i].end ? list.splice(i--, 1) : list[i](); }; !list.length && stop(); }, // 停止所有定时器队列 stop = function () { clearInterval(intervalId); intervalId = null; }; return function (url, ready, load, error) { var onready, width, height, newWidth, newHeight, img = new Image(); img.src = url; // 如果图片被缓存,则直接返回缓存数据 if (img.complete) { ready.call(img); load && load.call(img); return; }; width = img.width; height = img.height; // 加载错误后的事件 img.onerror = function () { error && error.call(img); onready.end = true; img = img.onload = img.onerror = null; }; // 图片尺寸就绪 onready = function () { newWidth = img.width; newHeight = img.height; if (newWidth !== width || newHeight !== height || // 如果图片已经在其他地方加载可使用面积检测 newWidth * newHeight > 1024 ) { ready.call(img); onready.end = true; }; }; onready(); // 完全加载完毕的事件 img.onload = function () { // onload在定时器时间差范围内可能比onready快 // 这里进行检查并保证onready优先执行 !onready.end && onready(); load && load.call(img); // IE gif动画会循环执行onload,置空onload即可 img = img.onload = img.onerror = null; }; // 加入队列中定期执行 if (!onready.end) { list.push(onready); // 无论何时只允许出现一个定时器,减少浏览器性能损耗 if (intervalId === null) intervalId = setInterval(tick, 40); }; }; })();

您可能感兴趣的文章:
jquery 图片预加载 自动等比例缩放插件
jQuery图片预加载 等比缩放实现代码
javascript 图片预加载的例子
使用jquery插件实现图片延迟加载技术详细说明
jQuery图片预加载(延迟加载)插件Lazy Load
jquery 图片预加载代码一例
Jquery 动态实现图片缩略的代码
jQuery图片展示插件 Zoomimage
jQuery实现图片放大预览实现原理及代码
js image对象预加载图片的方法详解

[关闭]
~ ~