Skip to content

JavaScript 图片预加载

Published: at 02:20 PMSuggest Changes

这个是简单版本的预加载图片

function preloadImage(url) {
  const img = new Image();
  img.src = url;
}

用 Promise 封装一下

const preloadImage = (src) => {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.onload = resolve;
    image.onerror = reject;
    image.src = src;
  });
};

const preloadImages = (srcs) => {
  return Promise.all(srcs.map(preloadImage));
};

preloadImages(['./img/2022-prize-list.png', './img/2022-pbg.png']).then(() => {
  console.log('images loaded');
});

后记


Previous Post
JavaScript 添加 CSS 属性
Next Post
MySQL 删除表