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

匆匆过客 提交于 2019-12-11 01:51:23

问题


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


回答1:


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




回答2:


What if you put the placeholder as background image behind the original image? If the image exists, it will cover the placeholder. If not, then nothing covers the placeholder and it will be visible.



来源:https://stackoverflow.com/questions/10265839/how-to-replace-nonexistent-images-with-a-placeholder-in-asynchronous-loading-fro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!