Preventing Broken Images from Displaying on HTML Pages
When developing a website, it is common to load images dynamically based on the current page URL. However, there may be situations where the image is not found, resulting in a broken image being displayed. To avoid this, there are a couple of techniques you can employ.
The first technique involves using the onerror
event handler in the <img>
tag. By adding the onerror
attribute and assigning a JavaScript function, you can remove the element from the DOM if the image fails to load. Here is an example:
1 | <img src="/{{$bookname}}.png" |
In this example, this
refers to the current <img>
element. By calling this.remove()
, the element will be removed from the DOM, preventing the broken image from being displayed.
While this approach works, it may not be the most optimal solution, as it relies on the assumption that all images will eventually be created and loaded properly. As a workaround, you can also display a fallback image when the original image is not found. Here is an example:
1 | <img src="/{{$bookname}}.png" |
In this case, this.onerror=null
is added to prevent an infinite loop if the fallback image is also not found. By assigning the fallback.png
as the new source using this.src
, you ensure that a valid image is displayed even if the original image is missing.
While these techniques can help prevent broken images from being displayed on your HTML pages, it is still recommended to ensure that all images are properly created and loaded. However, as a developer who may overlook image creation, these workarounds can serve as temporary solutions.
tags: [“HTML”, “image loading”, “onerror event”, “broken image”, “fallback image”, “dynamic image loading”]