我想预加载图像,但不一定想将它们附加到 DOM。如果我预加载图像,它会被有效地预缓存吗?
我的理解是,缓存是通过引用图像的 src
来工作的。从实践来看,为了预缓存而进行预加载似乎确实有效。然而,我不确定;这可能不可靠或对性能产生一些负面影响。
我正在使用图像构造函数来预加载。
const img = new Image();
img.src = imageArray[i].url;
最佳答案
是的,它确实有效。
function preloadImage(url){
const img = new Image();
img.src = imageArray[i].url;
}
但是,有两种方法。例如,将预加载延迟到页面加载之后:
function preloader() {
if (document.images) {
var img1 = new Image();
var img2 = new Image();
var img3 = new Image();
img1.src = "http://url/image-001.jpg";
img2.src = "http://url/image-002.jpg";
img3.src = "http://url/image-003.jpg";
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(preloader);
关于javascript - 将图像预加载到预缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58700466/