-2

i'm wondering how to avoid an image being loaded every time it's called?

here's a link to a working EXAMPLE and JSFIDDLE

var images = [
    'img/img1.jpg',
    'img/img2.jpg',
    'img/img3.jpg'
    ],

l = images.length

for(var i=0; i<l; i++){
    var img = new Image().src = images[i];
}

i=0

function changeBG(){
    $('body').css({ backgroundImage: "url("+ images[i++]+ ")" });
        if (i == images.length) {
            i = 0;
        }
}
changeBG();

setInterval(changeBG, 2000);

enter image description here

artrtrkli
  • 83
  • 1
  • 9
  • Creating one single image element and changing its source could address this issue in newer browsers, in Chrome at least. – SeinopSys Jun 29 '14 at 15:40
  • It works perfectly on FireFox ,not in Chrome . Your fiddle and Example also doesnt work on chrome properly.Its browser issue ,what can you do about it? – Pratik Joshi Jun 29 '14 at 15:43
  • For the record, outside of any development environment/mode your browser should handle caching automatically. If you watch the actual requests in chrome for example it's simply making a check to see if the file was modified since it was last downloaded - the server returns a 304 "not modified" response and the browser loads from the cache. *(Hint: watch the bytes transferred: ~61KB, ~84KB, ~29KB for the first 3 requests. 244B for all subsequent requests)* – Emissary Jun 29 '14 at 15:49
  • If it really bothers you I'd go down the route of dynamically [creating a new stylesheet with Javascript](http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript), adding entries for each of your images and then changing the `body` tag's `className` instead. – Emissary Jun 29 '14 at 15:55

1 Answers1

0

How about a different approach - quick edit, and needs some tweaking no doubt, like getting rid of the display:none entirely and use opacity instead, etc:

jsFiddle

CSS:

body
{
    width:100%;
    height:100%;
}

.bgImage
{
    display:none;
    width:100%;
    height:100%;

    position:absolute;
    top:0;
    left:0;
}

HTML:

<div id="background_image">
    <img id="bgImage_1" class="bgImage" src="https://dl.dropboxusercontent.com/u/59549499/example/img/img1.jpg">
    <img id="bgImage_2" class="bgImage" src="https://dl.dropboxusercontent.com/u/59549499/example/img/img2.jpg">
    <img id="bgImage_3" class="bgImage" src="https://dl.dropboxusercontent.com/u/59549499/example/img/img3.jpg">
</div>

JS:

curImage = 0;
nextImage = 1;

function changeBG()
{
    jQuery('#bgImage_' + nextImage).css('opacity', 0).show().animate({'opacity': 1}, 300);
    if(curImage > 0) jQuery('#bgImage_' + curImage).animate({'opacity': 0}, 300);

    curImage = nextImage;
    nextImage++;
    if(nextImage > 3) nextImage = 1;
}
changeBG();

setInterval(changeBG, 2000);
Geoff
  • 164
  • 1
  • 6