Loading images before cycling them as div background?
I have a standard webpage developed in php using CSS and currently a bit of javascript to cycle through some images for a offers div. You can see the site he开发者_运维百科re, this will not be it's final resting place this is a temporary site. If you look at the offers banner. When it switches to the next image it goes white whilst it loads the next image. Is there anyway of loading the next image before applying it to the div background property? Here is my javascript atm.
var c=0
var s
function offersCycle()
{
if (c%3==0){
document.getElementById('offers').style.background = "url(/images/1.jpg)";
}
if (c%3==1){
document.getElementById('offers').style.background = "url(/images/2.jpg)";
}
if (c%3==2){
document.getElementById('offers').style.background = "url(/images/3.jpg)";
}
c=c+1
s=setTimeout("offersCycle()",8000)
I tried using a set of new Images in the javascript and defining them before cycling them but they wouldn't apply to the CSS as this relies on a url and not an image itself? Any ideas appreciated. Cheers, Jordan
I would do something like this:
var c = 0, images = ["/images/1.jpg", "/images/2.jpg", "/images/3.jpg"];
for(var i=0; i<images.length; i++) {
var img = new Image();
img.src = images[i];
}
function offersCycle() {
document.getElementById('offers').style.background = "url("+images[c%images.length]+")";
c++;
}
var s = setTimeout(offersCycle, 8000);
By using an array, we simplify the logic and can use the same array to preload the images to cache them when the page first loads. This also allows you to add as many images as you want to the array without changing anything.
You could preload the images using Javascript.
Details here: https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5214317.html
精彩评论