Hello,
I am a beginner to jQuery, I am using the the latest version of jQuery. I am creating roll overs which when hovered on will change the background image that is used in the style sheet. Now since these images are large I want to preload them using javascript. The code that I am using to do that is-:
- var img1,img2,img3,img4;
var list=[ // Preloading the images to avoid flickering.
"images/hoverEffect/foo1.png",
"images/hoverEffect/foo2.png",
"images/hoverEffect/foo3.png",
"images/hoverEffect/foo4.png"
];
function preloadImgs(){
img1 = new Image(list[0]);
img1.src = list[0];
img2 = new Image(list[1]);
img2.src = list[1];
img3 = new Image(list[2]);
img3.src = list[2];
img4 = new Image(list[3]);
img4.src = list[3];
}
This function is called in the beginning of the page load.
A sample of my CSS code-:
- $("body").css('background-image', 'url(images/hoverEffect/foo1.png)' );
- $("#mainPage").html('<div id="description"><h1><i>
| Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. |
| Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. |
<br/><br/></p></div>');
- $("#description").css('background-color', '#333');
- $("#description").css('border-color', '#fff');
The following code is triggered every time there is a mouse hover over a rollover element.
Now very oddly my rollovers are not showing any flickering problems for the first few times I do a mouse hover, but if I leave the page unattended for about 6 secs, and then again when I do mouse hovers a on my rollovers the flickering again starts. It is as if I did not cache or preload my images.
Is there a way of preloading images with jQuery and storing them in the browser cache for at least as long I am on that page ???? I mean I am not saying that the images should only stay in the browser cache for the first 5 seconds but they should stay in the cache for as long as I am on that particular page.
Is there any way to do that ???
Thank You.