预加载 img 的方式。

Posted Hello World

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了预加载 img 的方式。相关的知识,希望对你有一定的参考价值。

原生方式:

var img = new Image();

img.onerror = function() {
    alert(‘img error‘);
};

img.onload = function() {
    img.onerror = img.onload = null;
    alert(‘img loaded‘);
};

img.src = ‘http://s1.bdstatic.com/r/www/cache/static/global/img/icons_1529edac.png‘;

jQuery:

var $img = $(‘‘);
$img.one(‘error‘, function(){
    alert(‘jquery img error‘);
});
$img.one(‘load‘, function(){
    alert(‘jquery img loaded‘);
});
$img.attr(‘src‘, ‘http://s1.bdstatic.com/r/www/cache/static/global/img/icons_1529edac22.png‘);

如果要判断这个图片已经加载过的,可以用 img.complete, 如果为 true,加载完毕;false 未加载。

但是 在 IE9 IE8 IE7 IE6 下,如果 只用(new Image()).src = ‘xxx.jpg‘,而并没有把 img appendTo body 里,图片就算加载完毕,但 img.complete 始终为 false, 而chrome 和 firefox 不需要 appendTo body,图片加载完以后 img.complete 为true。

而在 IE 和 chrome FF 下,img 就算没有 appendTo body, fiddler 抓包 图片也是 304 Not Modified,说明图片有总是有被加载。

以上是关于预加载 img 的方式。的主要内容,如果未能解决你的问题,请参考以下文章

收藏|分享前端开发常用代码片段

关于js----------------分享前端开发常用代码片段

预加载 img 的方式。

使用 jQuery 预加载目录中的所有图像

图片预加载

图片预加载 解决图片加载闪动问题