0

I've been trying to get this working, and not having 100% success, basically trying to load an image, if the source doesn't exist try a second image until it reaches a default one.

I have been trying the solution based on this question, however I am not using jQuery, so the accepted solution is no use to me, so trying the 2nd solution, which pretty much works, but doesn't seem to be (if that makes sense?). I can get it to test the second image we need, but then it doesn't seem to trigger the onload event again.

function topTenImages(){
 var topTenDiv = document.getElementById('toptenimg');
 var topTenImg = new Image();
 var ac = "tryout";
 var imageOrder = new Array(
  "/images/codespec/banners/"+ac+"_topten.gif",
  "/images/codespec/banners/"+ac+"_topten.jpg",
  "/images/banners/default_topten.png",
  "/images/banners/default_topten.jpg"
 );
 var errorCnt = 0;
 topTenImg.src = domainResources+imageOrder[errorCnt];
 topTenImg.onLoad = new function(){
  if(!checkImage(topTenImg)){
   if(errorCnt < imageOrder.length){
    var io = imageOrder[++errorCnt];
    topTenImg.src = domainResources+io;
   }
  }
 }
 topTenDiv.appendChild(topTenImg);
}

Yes I know that we could do this server side with php/perl/et al, but we are trying to limit our outgoing headers, so this seemed to be the best way of doing it. (Alternatives welcome). My other thought was to wrap it in a for loop on the array, and create a new object each time. But this seemed to make more sense.

Thanks, Psy

Community
  • 1
  • 1
Psytronic
  • 6,043
  • 5
  • 37
  • 56
  • A bit OT: Drop the `new` from `new function`. You only use `new` with the `Function` (note the capital) *constructor*, which is rarely used and not appropriate here. You don't use it with the `function` declaration. – T.J. Crowder Jan 18 '10 at 14:38
  • Thanks, I always get confused with when to and not to use new :) – Psytronic Jan 18 '10 at 15:56

1 Answers1

2

This should answer your question: http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called You just need to set onLoad first. Hopefully that will work:

 topTenImg.onLoad = function(){
  if(!checkImage(topTenImg)){
   if(errorCnt < imageOrder.length){
    var io = imageOrder[++errorCnt];
    topTenImg.src = domainResources+io;
   }
  }
 }
 topTenImg.src = domainResources+imageOrder[errorCnt];
Eric Mickelsen
  • 10,309
  • 2
  • 30
  • 41
  • +1 that's it, you need to set onload before setting the src. However, I still have a rest of distrust towards onload, as I *think* I've had instances where it still didn't fire. Not sure though. – Pekka Jan 18 '10 at 14:39