图片预加载的一个简明例子
2011-04-19
图片预加载技术的典型应用:如lightbox方式展现照片,无疑需要提前获得大图的尺寸,这样才能居中定位,由于javascript无法获取img文件头数据,必须等待其加载完毕后才能获取真实的大小然后展示出来,所以lightbox显示的图片的速度体验要比直接输出的差很多,而本文说提到的预加载技术主要针对获取图片尺寸。
效果演示
清空缓存
(浏览器会缓存加载过后的图片)
一段典型的使用预加载获取图片大小的例子:
var imgLoad = function (url, callback) {
var img = new Image();
img.src = url;
if (img.complete) {
callback(img.width, img.height);
} else {
img.onload = function () {
callback(img.width, img.height);
img.onload = null;
};
};
};
web应用程序区别于桌面应用程序,响应速度才是最好的用户体验。如果想要速度与优雅兼得,那就必须提前获得图片尺寸,如何在图片没有加载完毕就能获取图片尺寸?
- 结合flash加载图片,获取图片头部数据的尺寸?
- 在服务端保存图片尺寸数据?
- javascript通过占位方式获取图片头部数据的尺寸?
flash虽然很强大,但它与生俱来的缺点让人爱恨交织,加上很多移动设备不支持falsh无疑更是致命的伤,还是放弃吧。
这里不得不提到腾讯Qzone的lightbox相册,它就是这样做的。它能在图片没有加载完全的时候就居中放大图片,速度与优雅基本兼得。不过它仍然难以避免blog插入的外链图片的问题,也只能按传统的方式加载完毕才能展示。
十多年的上网经验告诉我:浏览器在加载图片的时候你会看到图片会先占用一块地然后才慢慢加载完毕,并且这里大部分的图片都是没有预设width与height属性的,因为浏览器能够获取图片的头部数据。基于此,只需要使用javascript定时侦测图片的尺寸状态便可得知图片尺寸就绪的状态。
实现代码:
// imgReady event - 2011.04.02 - TangBin - MIT Licensed
/**
* 图片头数据加载就绪事件
* @see http://www.planeart.cn/?p=1121
* @param {String} 图片路径
* @param {Function} 尺寸就绪 (参数1接收width; 参数2接收height)
* @param {Function} 加载完毕 (可选. 参数1接收width; 参数2接收height)
* @param {Function} 加载错误 (可选)
*/
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 check, width, height, newWidth, newHeight,
img = new Image();
img.src = url;
// 如果图片被缓存,则直接返回缓存数据
if (img.complete) {
ready(img.width, img.height);
load && load(img.width, img.height);
return;
};
// 检测图片大小的改变
width = img.width;
height = img.height;
check = function () {
newWidth = img.width;
newHeight = img.height;
if (newWidth !== width || newHeight !== height ||
// 如果图片已经在其他地方加载可使用面积检测
newWidth * newHeight > 1024
) {
ready(newWidth, newHeight);
check.end = true;
};
};
check();
// 加载错误后的事件
img.onerror = function () {
error && error();
check.end = true;
img = img.onload = img.onerror = null;
};
// 完全加载完毕的事件
img.onload = function () {
load && load(img.width, img.height);
!check.end && check();
// IE gif动画会循环执行onload,置空onload即可
img = img.onload = img.onerror = null;
};
// 加入队列中定期执行
if (!check.end) {
list.push(check);
// 无论何时只允许出现一个定时器,减少浏览器性能损耗
if (intervalId === null) intervalId = setInterval(tick, 40);
};
};
})();
