Home > Back-end >  How can I retrieve image error code using JavaScript or jQuery?
How can I retrieve image error code using JavaScript or jQuery?

Time:10-04

I am changing the src attribute of an image element. If there's an error I want to know the error status code.

CodePudding user response:

You can use Image API in Javascript, for know when image load fail:

function mountImage(src) {
  const img = new Image();
  
  img.src = src;

  img.onload = () => {
    // image loaded
  }

  img.onerror = () => {
     // image fail load
  }



}

CodePudding user response:

You could adapt this source example on mdn web docs. If you change the src attribute programmatically and need to check first if it gives an error code, it could do the job. Here a draft, I hope this is going to help you.

let changesrc = (newsrc) => {
  const myImage = document.getElementById('testimg');
  const myRequest = new Request(newsrc);

  fetch(myRequest).then((response) => {
    console.log(response.status);
    if(response.status == "200") {
      response.blob().then((myBlob) => {
        const objectURL = URL.createObjectURL(myBlob);
        myImage.src = objectURL;
      });
    }
  });
};
<button onclick="changesrc('https://picsum.photos/200');">test ok</button>
<button onclick="changesrc('https://picsum.photos/noway');">test not ok</button>
<img id='testimg' src="https://picsum.photos/200">

  • Related