开发者

How to go about writing a Javascript pre-loader?

I'm not talking about how to pre-load images using Javascript, I am thinking more along the lines of a Flash preloader which displays some sort of feedback while the SWF loads.

The site in question has heavy Javascript usage and requires many large images at p开发者_运维知识库age load so I wish to hide the site behind a loading screen till the initial images are all loaded.


I wrote a jQuery plugin called waitForImages that lets you do this.

The callbacks allow you to do whatever when each image has loaded...

$('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.


I have one written when I first learned JavaScript. I'm going to try to find it in a second. The basic idea is to have a hidden element that's outside the page, and load your image in there.

Beware, ugly code as I wrote this when i started. Also it probably is not exactly what you're looking for, though there are good comments. Just modify it and make it a generic function. Based on jQuery, for a javascript gallery:

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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜