我发现使用innerHTML克隆节点时。它将自动再次重新下载相同的源。有办法避免这种行为吗?
您无法真正避免这种行为-当<img>
元素插入DOM或src
更改时,浏览器将获得资源。
不过您可以减轻影响-有几种方法可供考虑:
304
响应时,将不会重新传输图像数据,但将使用本地缓存的版本。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);
});