onerror and onload when image acquisition fails

I recently encountered a problem in the project, when the image could not be loaded. On pc and mobile, the position of the picture is blank. But on the Apple pad, the position of the picture is a faint box, as shown in the figure

So I thought of adding a visibility: hidden to the picture that cannot be displayed; so that it is invisible, and the position is still retained. In the same way, it can also be replaced with a default image.

There are 2 events related to loading, onerror and onload

1. Use onerror to solve the problem of img loading failure

Take a look at the official website's introduction to the event

The onerror event is fired when an error occurs during document or image loading.

HTML tags that support this event:

<img>, <object>, <style>

JavaScript objects that support this event:

window, image

demo1. When the image acquisition fails, it is empty

//当图片加载失败时,隐藏图片
<img onerror="checkError()"/>
<script>
function checkError(e){
    e.target.style.visibility = 'hidden';
}
</script>

The experiment shows that 1. When the image address is empty, the event will be triggered. 2. When the picture has an address but no picture, the event will also be triggered when the acquisition fails 404

demo2. When the image acquisition fails, replace it with the default image

//当图片加载失败时,替换图片为default.png
<img onerror="checkError()"/>
<script>
function checkError(e){
    e.target.src = 'default.png';
}
</script>

But if the default image also fails to be acquired, it will enter an infinite replacement loop.

//当图片加载失败时,替换图片为default.png
<img onerror="checkError()"/>
<script>
function checkError(e){
    if(e.target.src == 'default.png'){
      return false
    }
    e.target.src = 'default.png';
}
</script>

2. Use onload to solve the problem of img loading failure 

Take a look at the official website's introduction to the event

The onload event occurs immediately after the page or image has finished loading.

onload is commonly used in <body> to execute a script once everything is fully loaded (including images, script files, CSS files, etc.)

HTML tags that support this event:

<body>, <frame>, <frameset>, <iframe>, <img>, <link>, <script>

JavaScript objects that support this event:

image, layer, window

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325965419&siteId=291194637