我不是在讨论如何pre-load images using Javascript,我更多地考虑Flash预加载器,它在SWF加载时显示某种反馈。
有问题的网站使用了大量的Javascript,并且在页面加载时需要很多大图像,所以我希望在加载屏幕后面隐藏网站,直到初始图像都被加载。
答案 0 :(得分:3)
我写了一个jQuery plugin called waitForImages,可以让你这样做。
回调允许您在每个图像加载时执行任何操作...
$('body').waitForImages(
function() {
// Called when all images have loaded.
},
function(loaded, total, success) {
// Called once each individual image has loaded.
// `loaded` is the number of images loaded so far.
// `total` is the total number of images to load.
// `success` is `true` if the image loaded and `false` if the image failed to load.
// `this` points to the native DOM `img` element.
},
// Set the third argument to `true` if you'd like the plugin to look in the CSS
// for references to images.
true
);
答案 1 :(得分:0)
我第一次学习JavaScript时写了一篇。我打算在一秒钟内找到它。基本思想是在页面外部放置一个隐藏元素,然后将图像加载到那里。
当我开始时,当我写这篇文章的时候,请注意,丑陋的代码。它也可能不是你想要的,尽管有很好的评论。只需修改它并使其成为通用函数。基于jQuery,对于javascript库:
this.preload = function(){
/*
* Preloads all the image to a hidden div so the animation won't glitch.
*/
if (document.getElementById("preload")){ // Checks for existance.
var preload = document.getElementById("preload"); // Gets the preload div if it exists.
} else {
var preload = document.createElement("preload"); // Creates the preload div if it doesn't exist.
$(preload).attr("id", "preload");
}
for (var i=0; i<this.aNodes.length; i++){ // Get all the image links
var img = document.createElement("img"); // Loads all the image in a hidden div.
$(img).attr("src", this.aNodes[i].href);
preload.appendChild(img);
}
}