我在下面写的函数是否足以在大多数(如果不是全部的话)当前常用的浏览器中预加载图像?
function preloadImage(url)
{
var img=new Image();
img.src=url;
}
我有一个图像URL数组,我循环遍历并为每个URL调用preloadImage函数。
我在下面写的函数是否足以在大多数(如果不是全部的话)当前常用的浏览器中预加载图像?
function preloadImage(url)
{
var img=new Image();
img.src=url;
}
我有一个图像URL数组,我循环遍历并为每个URL调用preloadImage函数。
当前回答
试试这个,我觉得这个更好。
var images = [];
function preload() {
for (var i = 0; i < arguments.length; i++) {
images[i] = new Image();
images[i].src = preload.arguments[i];
}
}
//-- usage --//
preload(
"http://domain.tld/gallery/image-001.jpg",
"http://domain.tld/gallery/image-002.jpg",
"http://domain.tld/gallery/image-003.jpg"
)
来源:http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
其他回答
您可以将此代码移动到index.html,以便从任何url预加载图像
<link rel="preload" href="https://via.placeholder.com/160" as="image">
是的。这应该可以在所有主流浏览器上运行。
这就是我所做的,用承诺:
const listOfimages = [
{
title: "something",
img: "https://www.somewhere.com/assets/images/someimage.jpeg"
},
{
title: "something else",
img: "https://www.somewhere.com/assets/images/someotherimage.jpeg"
}
];
const preload = async () => {
await Promise.all(
listOfimages.map(
(a) =>
new Promise((res) => {
const preloadImage = new Image();
preloadImage.onload = res;
preloadImage.src = a.img;
})
)
);
}
是的,这是可行的,但是浏览器会限制(4-8之间)实际的调用,因此不会缓存/预加载所有想要的图像。
更好的方法是在使用图像之前调用onload,如下所示:
function (imageUrls, index) {
var img = new Image();
img.onload = function () {
console.log('isCached: ' + isCached(imageUrls[index]));
*DoSomething..*
img.src = imageUrls[index]
}
function isCached(imgUrl) {
var img = new Image();
img.src = imgUrl;
return img.complete || (img .width + img .height) > 0;
}
HTML生活标准现在支持“预加载”
根据W3C HTML规范,你现在可以像这样使用JavaScript预加载:
var link = document.createElement("link");
link.rel = "preload";
link.as = "image";
link.href = "https://example.com/image.png";
document.head.appendChild(link);