4

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.

Bakudan
  • 19,134
  • 9
  • 53
  • 73
Bin Chen
  • 61,507
  • 53
  • 142
  • 183
  • 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 comes 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 Dec 30 '11 at 05:21
  • @jfriend00 i use code to bind, what is the effect corresponding to you description? – Bin Chen Dec 30 '11 at 08:36

3 Answers3

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.

John
  • 164
  • 2
  • 5
1

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;
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • I can't because my code needs to calculate each image's width&height to do some layout. and some images are load very slowly – Bin Chen Dec 30 '11 at 08:34
1

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

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

Community
  • 1
  • 1
Sang
  • 2,790
  • 2
  • 20
  • 17