3

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>
5
  • Pass this as an agument to reloadImage, and do thisArg.src = "example.com/image.png?reload=true" in the function. Commented Apr 3, 2021 at 20:34
  • Great! How do I also get the current src then add the "?reload=true" to it? The image source is not always "example.com/image.png", it might be "example.com/another_image.png" as well Commented Apr 3, 2021 at 20:36
  • You could be in danger of looping indefinitely - probably should have some break after a certain number of attempts - but better would be to find out why you are getting a 404 - is the image on a server that you have some control over? Commented Apr 3, 2021 at 20:37
  • ??? src property of the image is read/write string. Commented Apr 3, 2021 at 20:37
  • A Haworth the image comes from an API where the src is the API request. Sometimes it doesn't work right away, but when reloaded it works Commented Apr 3, 2021 at 20:40

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! How can this be modified so that the new src from reloadImage() becomes the original src of the image with "?reload=true" tacked onto it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.