views:

334

answers:

1

Hey Guys,

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

+2  A: 

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
+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