img tag onerror event

created at 10-12-2021 views: 193

Sometimes, the src picture in the img tag fails to load, and a fragment icon appears in the original picture position, which makes people very uncomfortable. How to make it more beautiful?

You can borrow the onerror event of the img tag. The img tag supports the onerror event. If an error occurs during the loading of the document or image, the onerror event will be triggered. You can use a picture that prompts an error instead of a picture that can't be displayed. code show as below:

<img src="images/logo.png" οnerrοr="javascript:this.src='images/logoError.png';">

When the image images/logo.png does not exist, the onerror event will be triggered, and the image/logoError.png image is specified for the img in onerror. That is to say, if the image images/logo.png exists, logo.png will be displayed, and if the image images/logo.png does not exist, logoError.png will be displayed.


If images/logoError.png does not exist, the onerror event will continue to be triggered, resulting in an infinite loop, so a Stack overflow at line: 0 error will appear when opening the webpage. Special note: If the picture exists but the network is not smooth, the onerror event may also be triggered.


Control it not to loop, the code is as follows:


     errImg() {
       let img = event.srcElement;
       img.src = require("../../assets/visualImg/null.jpg");
       img.onerror = null; //Prevent flash image control, don't keep beating
created at:10-12-2021
edited at: 10-12-2021: