The picture component of the applet itself has a binderror binding event that failed to load, so this solution is to work on the event of the binding.

First, the WXML and JS codes for the image binding are as follows:

<! -- Normal image -->
<image class="full-width" src="{{imgUrl}}" mode="widthFix" binderror="bindImgErr" data-resrc="{{imgUrl}}" data-name="imgUrl" lazy-load="false"></image>
Copy the code
page({
    bindImgErr(e) {
        const { name, resrc } = e.currentTarget.dataset;
        this.setData({
            [name]: resrc
        })
    }
})
Copy the code

The above code looks fine, but it isn’t. The following is a brief description of the specific problems encountered:

Images that fail are not automatically retried once

Since the address of the image in data-resrc is the same as the address of the image in SRC, the image does not automatically retry loading. Therefore, the address of resRC should be processed, such as adding a parameter t=1

page({
    bindImgErr(e) {
        const { name, resrc } = e.currentTarget.dataset;
        // Retry only once
        if(! resrc.includes('t=1')) {
            let url = ' ';
            if (resrc.includes('? ')) {
              url = `${resrc}&t=1`;
            } else {
              url = `${resrc}? t=1`;
            }
            this.setData({
              name: url, }); }}})Copy the code

Picture address

The image address in the above example is only a common form. In actual situations, we may encounter the image address in array, object and other complex scenes, as follows:

page({
    data: {
        imgUrl: 'https://xxx.xxx.com'.imgUrls: ['https://xxx.xxx.com'.'https://xxx.xxx.com'.'https://xxx.xxx.com'].product: {
            imgUrl: 'https://xxx.xxx.com',}}})Copy the code

Therefore, further processing of name is required:

<! -- Normal image -->
<image class="full-width" src="{{imgUrl}}" mode="widthFix" binderror="bindImgErr" data-resrc="{{imgUrl}}" data-name="imgUrl" lazy-load="false"></image>

<! - array -- -- >
<view wx:for="{{imgUrls}}">
    <image class="full-width" src="{{item}}" mode="widthFix" binderror="bindImgErr" data-resrc="{{item}}" data-name="imgUrl[{{index}}]" lazy-load="false"></image>
</view>

<! - object - >
<image class="full-width" src="{{product.imgUrl}}" mode="widthFix" binderror="bindImgErr" data-resrc="{{product.imgUrl}}" data-name="product.imgUrl" lazy-load="false"></image>
Copy the code
page({
    bindImgErr(e) {
        const { name, resrc } = e.currentTarget.dataset;
        // Retry only once
        if(! resrc.includes('t=1')) {
            let url = ' ';
            if (resrc.includes('? ')) {
              url = `${resrc}&t=1`;
            } else {
              url = `${resrc}? t=1`;
            }
            this.setData({
              [`${name}`]: url, }); }}})Copy the code