javascriptjqueryimagebroken-image

How to replace nonexistent images with a placeholder in asynchronous loading from database


I have a database with images that i need to load on-the-fly per user's request. The images would go as background images of separate s in an encompassing div container... something like image scroller.

The database is currently a local database but this is not my issue.

the issue is that the database may not have all the images that i have requested...and i may get one or more images that are non-existent... and since things are asynchronous on the database front and the loading image front as well, i am not sure how to go about replacing a non-existent image with a standard placeholder image. I cannot do it on the fly in a loop since that executes way before loading even happens. I tried using .Load and .error, but i am not sure how i can do that on a background image.

Is there a standard and simple way to deal with this.. preferably without plugins since i have many as is...


Solution

  • It seems i could not get away from having to create another DOM elem. Here is what i am now using:

    <div style="background:url(providerSrc)">
    <img
         style="display:none" 
           src="providerSrc"
       onerror="this.parentNode.style.backgroundImage='url(fallbackSrc)'"  
       />
    </div>
    

    This is taken from: http://www.daveoncode.com/2010/08/20/image-background-fallback-img-tag-error-handlers/

    If you know of 'better' solution please reply