preface

Different browsers display different ICONS for loading failed images, so it is important to have a default failed image.

Just a few days ago, I dealt with the error default picture of the company’s home page, so I would like to share this article before my memory disappears.

error

The IMG tag has an error event that catches exceptions and is easy to use

<img src="abc.xxx" alt="xxx" class="cs-img" />
Copy the code
<img src="abc.xxx" alt="xxx" class="cs-img" onerror="this.src = 'xxxx.png'"/ >;/ / or
var img = document.querySelector(".cs-img");
img.addEventListener("error".function(e) {
  e.target.src = "xxxx.png";
});
Copy the code

global

The above method is fine, but it requires us to manage the images manually. This can be very expensive to maintain, and you may just want to deal with the image failure uniformly.

Could be unified to the error of monitoring events, we hope to complete, but the picture of the error at the stage of the second stage is the target event model, is not going to bubble up, but also can through the window. The addEventListener. Error to finish listening.

By the way the window. The addEventListener. The error can not only listen to the picture of the failure can also be listening to CSS, js, such as loading errors, pay attention to distinguish the window. The onerror and window addEventListener. The difference between the error, The former is a JS runtime error, the latter is a resource error, for the event model online examples are many, do not expand here.

Let’s see how that works. Okay

window.addEventListener(
  "error".function(event) {
    var dom = event.target;
    if (/img/i.test(dom.nodeName)) {
      dom.src = "xxxx.png"; }},true
);
Copy the code

Note that the second argument to addEventListener must be true, and the default is false, indicating that it only starts during the bubble phase, but as mentioned above the image error event does not bubble up and therefore will not be caught.

Retry count

The above code does not take into account that the alternative SRC will fail. If the alternative SRC fails, it will cause the image to retry indefinitely.

window.addEventListener(
  "error".function(event) {
    var dom = event.target;
    if (!/img/i.test(dom.nodeName)) {
      return;
    }
    // There is no null return
    var retry = +dom.getAttribute("data-retry");
    if (retry >= 3) {
      // Absolutely safe picture
      dom.src =
        "data:image/gif; base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
    } else {
      dom.src = "xxxx.png";
      dom.setAttribute("data-retry", (retry += 1)); }},true
);
Copy the code

Dynamic filling

Finally share a dynamic template renders the web page (for example, the content of the web pages from the background of the HTML editor directly insert) how to monitor the error, if you don’t consider compatibility can use Windows in the head. The addEventListener. Error method, But if you want high compatibility try the following.

const img = Array.prototype.slice.call(document.images);
for (let i = 0; i < img.length; i++) {
  var dom = img[i];
  const image = document.createElement("img");
  image.src = dom.src;
  image.style.display = "none";
  document.body.appendChild(image);
  image.onerror = function(event) {
    dom.src = "xxxx.png";
    document.body.removeChild(image);
  };
  image.onload = function() {
    document.body.removeChild(image);
  };
}
Copy the code

As mentioned above, if the content is inserted directly through THE HTML code, we may not hear the default error event of the image, so we can retry all the IMG after the page is loaded, and specify an error event for the IMG.

The last

For the sake of demonstration, I have not made any compatibility supplement for the above code, but in actual production, the above code needs some syntax of Polyfill, especially DOM. I recommend some simple methods to convert the above example into jquery syntax.