且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更改src时图像加载时的jQuery回调

更新时间:2023-12-04 22:59:04

基于我大约一年前所做的一些测试,当从一个值更改图像的.src时,我发现没有可靠的方法来获取加载事件到另一个.因此,我不得不求助于加载新图像,并在加载新图像时用新图像替换我拥有的图像.该代码已经在数百个网站(幻灯片使用)中成功运行了大约一年,所以我知道它可以工作.

Based on some testing I did about a year ago, I found no reliable way to get a load event when changing the .src of an image from one value to another. As such, I had to resort to loading a new image and replacing the one I had with the new one when the new image was loaded. That code has been running successfully in several hundred web sites (it's used by a slideshow) for about a year now so I know it works.

如果在新图像上设置.src属性之前设置了加载处理程序,则将可靠地获得load事件.这是我今天早些时候写的一些捕获负载事件的代码:

If you set the load handler BEFORE you set the .src property on a new image, you will reliably get the load event. Here's some code I wrote just earlier today for capturing the load event: jQuery: How to check when all images in an array are loaded?.

在设置.src之前,附加事件处理程序的这段代码对我尝试过的现代浏览器有效(我没有测试旧的浏览器):

This code that attaches the event handler BEFORE setting the .src works for me in the modern browsers I've tried it in (I didn't test older browsers):

    $("img").on("load", function() {
        // image loaded here
    }).attr("src", url);

您可以在这里看到它的工作: http://jsfiddle.net/jfriend00/hmP5M/,然后您就可以使用该jsFiddle测试您想要的任何浏览器.只需单击该图像即可使其加载新图像.它循环遍历三个不同的映像(每次设置.src),每次都唯一地加载其中两个(永远不会从缓存中加载),并从缓存中唯一地加载它们,以便测试这两种情况.每当调用.load处理程序时,它将在屏幕上显示一条消息,以便您查看是否调用了它.

You can see it work here: http://jsfiddle.net/jfriend00/hmP5M/ and you can test any browsers you want using that jsFiddle. Just click on the image to cause it to load a new image. It cycles through three different images (setting .src each time), loading two of them uniquely every time (never from the cache) and one from the cache in order to test both cases. It outputs a message to the screen whenever the .load handler is called so you can see if it's called.