图片预载的简单实现,配合 Promise 还是很方便滴!

function loadResource(data) {
  return new Promise((reslove, reject) => {
    Promise.all(
      data.map(
        ({ name, path }) =>
          new Promise((resolve, reject) => {
            const img = new Image();
            img.src = path;
            img.addEventListener("load", () => {
              resolve({ [name]: img });
            });
            img.addEventListener("error", reject);
          })
      )
    )
      .then(list => {
        reslove(
          list.reduce((prev, curr) => Object.assign(prev, curr)),
          {}
        );
      })
      .catch(reject);
  });
};

使用方法如下:

/* name:为图片资源名称,加载完成后引用资源时使用
   path: 图片路径
*/
const imagesList = [{name:"logo",path:""}];

loadResource(imagesList).then(res=>{

  ...

}).catch(err=>{
  console.log(err);
})