JavaScript load pictures asynchronously

created at 11-15-2021 views: 1

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 => {
Please log in to leave a comment.