使用innerHTML或cloneNode克隆它们时,是否有避免重新下载源(图像,音频,图像)的方法?

问题描述 投票:0回答:1

我发现使用innerHTML克隆节点时。它将自动再次重新下载相同的源。有办法避免这种行为吗?

javascript html browser
1个回答
0
投票

您无法真正避免这种行为-当<img>元素插入DOM或src更改时,浏览器将获得资源。

不过您可以减轻影响-有几种方法可供考虑:

  1. 使用有效的缓存。当克隆的图像产生304响应时,将不会重新传输图像数据,但将使用本地缓存的版本。
  2. 使用服务工作者来缓存映像,并使用“缓存优先”策略,其中服务工作者总是立即以本地缓存的版本进行响应。
  3. 对图像进行fetch,创建数据URL,并将数据URL用作原始图像和克隆图像的源。请注意,由于编码的原因,数据URL大于实际的二进制数据。

这里是(3)的样本:

const img = new Image();
document.body.appendChild(img);
fetch('https://example.com/image.jpg')
.then(res => res.blob())
.then(blob => URL.createObjectURL(blob))
.then(dataUrl => {
  // load the image via the created data URI
  img.src = dataUrl;
  // clone the image
  setTimeout(() => {
    const clone = img.cloneNode();
    document.body.appendChild(clone); // won't request the image from the server again.
  }, 1000);
});
© www.soinside.com 2019 - 2024. All rights reserved.