Reputation: 153
I have an image that sometimes returns a 404 error. To get the image to load, it usually works if the image src is slightly modified, for example adding "?reload=true
" to the end of it. How do I do this using JavaScript?
<img src="example.com/image.png" onerror="reloadImage()">
<script>
function reloadImage() {
// Set img src to "example.com/image.png?reload=true"
}
</script>
Upvotes: 3
Views: 3990
Reputation: 46602
Try passing the element into the function, also clear the error event else it could infinite loop.
function reloadImage(img) {
img.onerror = null
let url = new URL(img.src)
url.searchParams.set('reload', 'true')
img.src = url.toString()
}
<img src="example.com/image.png" onerror="reloadImage(this)">
The ideal solution would be to track down why it's erroring in the first place and fix that.
Upvotes: 4