开发者

Animation with image preloading

开发者 https://www.devze.com 2023-03-30 21:47 出处:网络
I have a list of objects MyObject and that looks like this: var Obj1 = {\'ImgTop\':\'500px\',\'ImgLeft\':\'200px\',\'ImgSrc\':\'/image1.jpg\'}

I have a list of objects MyObject and that looks like this:

var Obj1 = {'ImgTop':'500px','ImgLeft':'200px','ImgSrc':'/image1.jpg'}
var Obj2 = {'ImgTop':'300px','ImgLeft':'100px','ImgSrc':'/image2.jpg'}
开发者_如何学Python

I load these objects into an array like this:

var AnimCycle = new Array(2);

AnimCycle[0] = Obj1;
AnimCycle[1] = Obj2;

In my code, there are actually 15 objects loaded in the array. I have function that gets called recursively and inside the function, I have this line:

$('#HomeImg').attr('src', AnimCycle[PanelID].ImgSrc); 

The problem is that the loading of the image happens when the line is triggered. How can I make the images preload?

Thanks for your suggestions.


Here is a simple script which helps to load images before hand using javascript.

    $.each(data, function(index, item) {
        var tempImage = new Image();
        tempImage.src = item.url;
        preloadedImages.push(tempImage);
    }


where data as an array of image data 
data=
{
   name:'NameofImage',
   url:'http://www.website.com/image1.jpg',
}

To display the images you can simply add the images to the DOM

 $("img").attr({
                src: item.src
            }).appendTo("#target");

I have a simple jsfiddle which demonstartes the script. It takes data from an ajax request and pre-loads the images. When the user does a mouseover the target it attaches the image to the DOM.

Below is the screenshot showing the images are being loaded at the time the page gets loaded:


Animation with image preloading




this reference link argues that images loaded in div which are hidden might not be pre-loaded in some of the browsers like Opera. I thought haven't verified it.

There might be other ways to load images using css if you do not want to use javascript

Hope this helps


Put all of your images in a hidden div in the html:

<div style="display:none">
    <img src="/image1.jpg" />
    <img src="/image2.jpg" />
</div>

They will be downloaded when the page loads, but they won't be displayed. Your JavaScript can remain as is.

If you want to do it with script, put this in your ready handler:

var imgPreloader = $("<div>").hide().appendTo("body");
$.each(AnimCycle, function() {
    $("<img>").src(this.ImgSrc).appendTo(imgPreloader);
});
0

精彩评论

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