Preface
In the past, I posted an answer in SO about how to replace broken images. And the code is
window.addEventListener( |
And the point is :
Put the code in the head and executed as the first inline script. So, it will listen the errors happen after the script.
Use event capturing to catch the errors earlier, also for those events which don’t bubble.
Use event delegation which avoids binding events on each image.
Give the error img element an attribute after giving them a backup.png to avoid error of the backup.png and subsequent infinite loop like below:
img error->backup.png->error->backup.png->error->,,,,,
I thought the answer is almost perfect. But it turns out there is more scenes I don’t know.
No Src?
Until Chrome 70.0.3538.102 in win7, code below wouldn’t trigger error event.
<img /> |
But code below would trigger!
<img src="" /> <img src /> |
That does make sense. However, img
without src
wouldn’t hidden. They would have 1px border like:
In this case, we may have to do something about that. For instance,
img:not([src]) { |
or a default backgroundImage
which will work on img
though 1px border is still there.
img:not([src]) { |
BackgroundImage Error?
I still can’t find a perfect solution for backgroundImage
. The best answer in SO is like:
.app__bg_img_box { |
And the cons is obvious.
- You have to take care of the transparency problem of the target image.
- Users can see the toggle between target image and default image.
- A little flaw is that default image will always be downloaded.
Another way I figured out is like code below. Here is the simplest code:
let backgroundDivs = Array.from(document.querySelectorAll('.app__bg_img_box')) |
It will work well in most simple scenes but the cons is also obvious:
- Code will be more complicated if you want to deal with multiple backgroundImages.
- Each time you updated your dom structure, you may have to run the code above if you have add new divs with backgroundImage.
Ending
If lucky enough, we may have the new API in Images which would make code below work.
background: image('target.gif', 'fallback.gif'); |