admin管理员组

文章数量:1415099

I am using <img> onload function to trigger the resize action on the image that has been loaded. But I found if in one webpage there is two or more <img>s with the same "src", which means the image is the same, the latter <img>'s onload() function will not be invoked. How to make sure that all the <img>s are properly resized even when there are some <img>s with the same src?

Thanks.

I am using <img> onload function to trigger the resize action on the image that has been loaded. But I found if in one webpage there is two or more <img>s with the same "src", which means the image is the same, the latter <img>'s onload() function will not be invoked. How to make sure that all the <img>s are properly resized even when there are some <img>s with the same src?

Thanks.

Share Improve this question edited Dec 30, 2011 at 5:04 Bakudan 19.5k9 gold badges55 silver badges75 bronze badges asked Dec 30, 2011 at 4:59 Bin ChenBin Chen 63.4k57 gold badges148 silver badges185 bronze badges 2
  • 1 If the .onload handler is set before the .src property is set on the img tag, the onload handler should fire even if the image es from the browser cache. If you set .src first (or it's already set in your page's HTML), and then set .onload, it may be too late. – jfriend00 Commented Dec 30, 2011 at 5:21
  • @jfriend00 i use code <img onload="function..." /> to bind, what is the effect corresponding to you description? – Bin Chen Commented Dec 30, 2011 at 8:36
Add a ment  | 

3 Answers 3

Reset to default 2

This is happening because your browser is actually caching the first image. So when you attempt to load the same "src" again, it's cached locally and never actually fires an onload. To get it to load at all times, you could append on a unique value to the query string.

Instead of using a separate onload handler for each <img/>, why not just use a single onload event for the window? This event fires after everything (like all the images) have loaded, so you could just process each image in that single handler. Something like:

function processAllImages()
{
    var imgElts = document.getElementsByTagName('img');
    for (var i=0; i<imgElts.length; i++)
    {
        processImage(imgElts[i]); // TODO write this function
    }
}

window.onload = processAllImages;

I asked similar question before.
Check this out: Javascript/jQuery: How to detect img is fully downloaded or not?

In short, you can use 'plete' property of img tag.
check it before you bind load event.

本文标签: jqueryjavascript img onload()Stack Overflow