Skip to content

image.onload not firing twice in IE7

It works in IE6, and FireFox; but for some reason not in IE7.

Using ASP.NET on the Page_Init I populate a list of chapters that are links to the image in the book as well as a Javascript array which holds the pageIDs.

ex.

Chapter 1 –> href=”javascript:seePage(4);”

Here is the actual code I am using:

var availablePages = ['1002_001','1002_002','1002_003','1002_004','1002_005'];

function seePage(index) {
    $get('imgSingle').src = 'graphics/loading.gif';
    var img = new Image();
    img.src = 'get.jpg.aspx?size=single&id=' + availablePages[index];
    img.onload = function() {
         var single = $get('imgSingle');
         single.src = img.src;
    }
}

When I click on Chapter 1, the image loads fine across the board (IE6,7,FF) and clicking on a second chapter link also works; however, in (and only in) IE7 does clicking on the same chapter twice (chap1, chap2, then chap1 again) does the image get stuck on the ‘loading’ image…

Answer

It’s caused because IE will cache the image, and the onload event will never fire after it’s already been loaded.

You need to position the onload event before the src.

var availablePages = ['1002_001','1002_002','1002_003','1002_004','1002_005'];

function seePage(index) {
    $get('imgSingle').src = 'graphics/loading.gif';
    var img = new Image();
    img.onload = function() {
         var single = $get('imgSingle');
         single.src = img.src;
    }
    img.src = 'get.jpg.aspx?size=single&id=' + availablePages[index];
}