JavaScript load pictures asynchronously

created at 11-15-2021 views: 4

1. Usage scenarios

In the case of slow image access, you can give the image priority to set a gray waiting to be loaded image, and when the image is loaded, replace the original gray placeholder image. When the picture is not loaded, the structure is not messy, and the page effect is achieved;

2. JS implementation

// Load pictures asynchronously
export function loadImageAsync(url) {
   return new Promise(function(resolve, reject) {
     const image = new Image();

     image.src = url;

     image.onload = function() {
       resolve(image); // return img object
       resolve(url); // url address can also be returned
     };

     image.onerror = function() {
       reject(new Error('Could not load image at '+ url));
     };
   });
}

Introduce when you need to load pictures asynchronously.

import {loadImageAsync} from "Address"
const imgUrl = DefaultImg;
const dataImg = "Image request address";

loadImageAsync(dataImg).then(res => {
     imgUrl = res; //Assign a new url
}).catch(err => {
     console.log(error);
})
created at:11-15-2021
edited at: 11-15-2021: