【问题标题】:How to speed up JavaScript image loading如何加快 JavaScript 图像加载
【发布时间】:2020-10-16 14:05:24
【问题描述】:

我有一个网站需要在页面加载时加载 10 张图片。但是,在将图像插入DOM 之前,我需要对图像执行一些操作。

当我使用 fetch 没有甚至执行任何操作然后我将它们插入到页面中加载图像时,页面加载时间比使用相同图像测试时长几倍但将它们放入<img src=="url" 标签中。我知道这是因为 JavaScript 是单线程的,浏览器加载 HTML 比 JS 快得多。但是我可以做些什么来加快使用fetch 检索图像? 示例:

for (let i =0; i < 10; i++) {
    const imageBlob = await fetch('https://picsum.photos/300/200').then(response => response.blob());
    const url = URL.createObjectURL(imageBlob);
    div.style.backgroundImage = 'url(' + url + ')';

}

我知道使用 Service Worker 可能有助于缓存 fetch 请求,但解决此问题的最佳方法是什么?

【问题讨论】:

  • 有什么意义?执行操作后,您可以 imageElement.src = 'url.png';。您甚至可以动态创建imageElement

标签: javascript xmlhttprequest fetch service-worker


【解决方案1】:

您可以在服务器/网站上本地下载图像,因此:

const imageBlob = await fetch('./images/200.jpg').then(response => response.blob());

这将提高速度,因为它不需要尝试从外部来源获取。

【讨论】:

  • 我需要在前端执行操作。
【解决方案2】:

首先,确保您的服务器使用 HTTP/2 来提供更快的下载。然后,您可以异步处理每个图像响应以获得更好的性能。

const images = [...]

Promise.all(images.map(url => fetch(url).then(processImageResponse))
  .then(allImagesProcessed)

async function processImageResponse(response) {
  // consider ArrayBuffer here instead: response.arrayBuffer()
  const blob = await response.blob();
  ...
}

// receives results[] of what each processImageResponse() returns
function allImagesProcessed(results) {...}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 2019-05-28
    • 1970-01-01
    • 2018-12-29
    • 2016-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多