开发者

Load and display multiple animated gifs at the same time (synchronised) with Javascript

I'm by no means any kind of coder or programmer, but I've been trying to load and display some gifs so that they all animate from the beginning at the same time. In other words, I need them to be synchronised.

I've done a lot of Googling and what I've come up with seems to work with Chrome/Safari and Firefox, but as usual, Internet Explorer refuses to cooperate.

My current code is this:

var images = ["thephoto1", "thephoto2", "thephoto3", "thephoto4", "thephoto5"];

function initImages() {
    for (var i = 0; i < images.length; i++) {
        imageId = images[i];
        image = document.getElementById(imageId);
        image.style.visibility = "visible";
    }
}  

function preloadImages(urls) {
    var img = new Array();
    for (var i = 0; i < urls.length; i++) {
        img[img.length] = new Image();
        img[img.length - 1].src = urls[i];
    }
}

window.onload = function() {
    var img = new Array(
        "http://desmond.imageshack.us/Himg391/scaled.php?server=391&filename=countdown.gif&res=medium",
        "http://icanhascheezburger.files.wordpress.com/2010/11/funny-pictures-gif-cat-love.gif",
        "http://i52.photobucket.com/albums/g9/cpchick/Random%20Gifs/therock.gif",
        "http://www.mobileapples.com/Assets/Content/Screensavers/dc_1owy86mw.gif",
        "http://www.pptbackgrounds.fsnet.co.uk/images/powerpoint-countdown-u1.GIF"
    );
    preloadImages(img);
    initImages();
}

With some added CSS:

.preload
    {
       visibility: hidden;
    }

It's basically this and this script combined.

You can view a live example here: http://jsfiddle.net/AN9uB/

Some possible methods or potentially helpful posts:

  • Restart an animated GIF from JavaScript without reloading the image.
  • Javascript to only display animated gif when loaded.

However from reading the comments on those links, I'm not entirely sure they're possible.

The test gifs I'm using are just random images I found and a small forewarning, some of the images are fairly large since I needed to test a variety gifs ranging in size and duration. All of the gifs loop except for the first countdown image which only plays once.

On some occasions the first countdown image doesn't play at all (it's stuck on 10) when viewing the page with Firefox 3.6.18, but otherwise the rest of the gifs all load and display at the same time.

The main problem is that I cannot think of a way to make this work with Internet Explorer. I thought perhaps to preload the images and then refresh the page via javascript. It's an ugly solution, but I think it 开发者_StackOverflow社区would work.

Flash is the obvious tool to be doing this kind of thing in, but the friend who I'm making this for only uses gifs.

Is there a more elegant solution that works across all major browsers? Also ideally, to only use Javascript, not JQuery.

Thanks for any help.


Well, you're not really preloading the images, because you're only calling the preloadImages function after the pages has loaded, i.e. after the actual IMG tags in the html have been read, and the browser's probably started downloading them. The last part may depend on the visibility:hidden style, but I'm not sure - at least I don't expect all browsers to agree on what to do in that case.

Also, you have the URLs defined both in the JavaScript, and in the HTML. That's both redundant and also harder to change later.

I must admit I have no idea if this will work right everywhere, but you might try

  1. only having the image URLs in JavaScript - you can then add then into the HTML, when they're ready

  2. using the onload event handler on the JS Image objects to assert that an image has been loaded. Once they've all loaded, add them to the document (i.e. the page).

Now, I don't know when a given browser starts the animation-clock on a gif. If it starts the moment the gif has been loaded, there's not much you can do, since the gif's won't load at the same time. If, however, they first start animating when they're placed in the document (which seems probable, but never trust a browser), then there's a chance.

// This function will add an array of images to div#images
function showImages(images) {
    var container = document.getElementById("images"); // get the #images div
    for( var i = 0, l = images.length ; i < l ; i++ ) {
        var img = document.createElement('IMG'); // create the IMG tag
        img.src = images[i].src; // set the src - the image should be preloaded when this happens
        container.appendChild(img); // add the IMG tag to the #images div
    }
}

// This one will create JS Image objects from an array of URLs
function loadImages(urls) {
    var remaining = urls.length; // the images still waiting to be fetched
    var images = []; // empty array to hold the created Image objects

    // this function will be called for Image object that is loaded
    var onloadHandler = function() {
        remaining--; // decrement the number of remaining images
        if( remaining < 1 ) {
            showImages(images); // if all images have loaded, add them to the page
        }
    };

    // create an Image object for each URL
    for( var i = 0, l = urls.length ; i < l ; i++ ) {
        var img = new Image();
        img.onload = onloadHandler; // set the onload-handler before setting the src
        img.src = urls[i];
        images.push(img); // add the Image object to the images array
    }
}

window.onload = function() {
    var urls = [
        "http://desmond.imageshack.us/Himg391/scaled.php?server=391&filename=countdown.gif&res=medium",
        "http://icanhascheezburger.files.wordpress.com/2010/11/funny-pictures-gif-cat-love.gif",
        "http://i52.photobucket.com/albums/g9/cpchick/Random%20Gifs/therock.gif",
        "http://www.mobileapples.com/Assets/Content/Screensavers/dc_1owy86mw.gif",
        "http://www.pptbackgrounds.fsnet.co.uk/images/powerpoint-countdown-u1.GIF"
    ];
    loadImages(urls);
};

Here's a jsfiddle of it all: http://jsfiddle.net/Frqys/2/

Again, I have no idea if this'll actually work in every browser. It seems ok in Safari, Chrome and Firefox (all on Mac OS), but it's impossible to be sure. I'd advise you to copy a gif file a number of times, and give each file a different name, so it'll have a unique URL. That should prevent it from caching, and keep its animation clock separate. Then try loading all those GIFs instead of a bunch of different ones, and see if they stay in sync.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜