如何编写Javascript预加载器?

我不是在谈论如何使用Javascript预加载图像 ,我正在考虑更多的Flash预加载器,它在SWF加载时显示某种反馈。

有问题的网站有大量的Javascript使用,并且在页面加载时需要很多大图像,因此我希望在加载屏幕后隐藏网站,直到初始图像全部加载。

我写了一个名为waitForImages的jQuery插件 ,可以让你这样做。

回调允许您在每个图像加载时执行任何操作…

 $('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 ); 

jsFiddle 。

我第一次学习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