简体   繁体   English

浏览器图像缓存和jQuery.load()问题

[英]Browser image cache and jQuery.load() issue

Code example: 代码示例:

var img = $("img");
var n = img.length;
var i = 0;
function loadImg(i) {
    if( i < n ) {
        $(img[i]).load( function() {
            console.log("img["+i+"] loaded");
            i++;
            loadImg(i);
        });
    } else {
        console.log("img["+i+"] loaded");
        return false;
    }
}
loadImg(0);

This code works, but when image already in a browser cache - jQuery.load is not firing. 此代码有效,但是当图像已经存在于浏览器缓存中时 - jQuery.load未触发。 How can I check to see if the picture is in a browser cache and forcibly fire jQuery.load? 如何检查图片是否在浏览器缓存中并强制触发jQuery.load?

Thanks. 谢谢。

Paul Irish has written a neat little plugin for that. 保罗爱尔兰为此写了一个整洁的小插件。 It does exactly what you want, including images loaded from cache: 它完全符合您的要求,包括从缓存加载的图像:

https://github.com/paulirish/jquery.imgloaded https://github.com/paulirish/jquery.imgloaded

I've updated your fiddle with the above plugin included. 我用上面的插件更新了你的小提琴。 This should answer your question: 这应该回答你的问题:

http://jsbin.com/acuhaf/9/edit http://jsbin.com/acuhaf/9/edit

The jQuery documentation says: jQuery文档说:

Caveats of the load event when used with images 与图像一起使用时加载事件的注意事项
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. 开发人员尝试使用.load()快捷方式解决的常见挑战是在图像(或图像集合)完全加载时执行函数。

There are several known caveats with this that should be noted. 应该注意有几个已知的警告。
These are: 这些是:
- It doesn't work consistently nor reliably cross-browser - 它不能一致地工作,也不能可靠地跨浏览器
- It doesn't fire correctly in WebKit if the image src is set to the same src as before - 如果图像src设置为与之前相同的src,则在WebKit中无法正确触发
- It doesn't correctly bubble up the DOM tree - 它没有正确地冒泡DOM树
- Can cease to fire for images that already live in the browser's cache - 对于已经存在于浏览器缓存中的图像,可以停止触发

You may want to use other library to preload images. 您可能希望使用其他库来预加载图像。 I would recommend PreloadJS 我会推荐PreloadJS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM