开发者

jQuery Preloading images for animation

开发者 https://www.devze.com 2023-01-30 09:37 出处:网络
I know there are heaps of jQuery preloading threads, and I\'ve read through most of them but still can\'t seem to find the solution to my problem.

I know there are heaps of jQuery preloading threads, and I've read through most of them but still can't seem to find the solution to my problem.

I have a "stop motion" animation which is built via jQuery using queue and based on the sequential naming of images. I don't want to run this animation until all the images required for it have been loaded. Spriting is not an option at the moment as there are different animations for different product types, and all the images have already been generated by the client.

My preload code at the moment is as below:

function preloadImages($img, $frames){
    var $imgsrc = $img.attr("src");
    var $getext = $imgsrc.split('.');
    var $ext = $getext[1];
    var $exploded = $getext[0].split('_');
    var $new开发者_运维问答src = "";
    for (var i=1; i <= $frames; i++){
        for (var j=0; j < $exploded.length-1; j++){
            $newsrc = $newsrc + $exploded[j] + "_";
        }
        $newsrc = $newsrc + i + "." + $ext;
        var image_preload = new Image();
        image_preload.src = $newsrc;
    }
}

Where frames is the number of total images in the sequence (6 or 12 at this stage), and the naming convention for images is as follows:

Brand_Product_Category_ProductID_SequenceNo.jpg.

What I'm trying to do is not load up the div holding the starting image until all of these images have been preloaded using the snippet below in document ready, but this doesn't seem to be working correctly, i.e., the holder is shown before all the required images have been preloaded, and consequently the animation doesn't run smoothly.

$(".holder").hide();
preloadImages($(".holder img"), 6);
$(".holder").fadeIn("slow");

I guess I need some sort of callback, though I'm not sure how to implement it.


The problem is this:

When you assign a value to the src field of an Image object, it does just that: changes the src attribute. The browser still needs to load the image from wherever the src attribute points.

You can define a handler for the 'load' event of an Image... so you're going to need to use something along those lines.

One approach would be to define a list of images that need to be loaded. Each time an Image is loaded, set a flag in the array. Periodically, check the array and, once all the flags are set, indicating that all images are loaded, you can fade in your div.

0

精彩评论

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