0

i had this Background Change on Scroll is flickering question for a few days. It will work on my computer. But when I upload it to the server the background images are still flickering while scrolling down the page.

My code looks now like this: (yes maybe there are tooo many images, but i have not idea to improve this)

Snippet of my js code:

function preloadImages() {
    for (i = 0; i < arguments.length; i++) {
        imgs[i] = new Image();
        imgs[i].src = arguments[i];
    }

FULL JS CODE :

http://jsfiddle.net/SEt53/

I hope someone can help me !

Community
  • 1
  • 1
Dennis
  • 137
  • 1
  • 2
  • 14

1 Answers1

1

You're changing the background image no matter what as the user is scrolling down. The best way to improve this would be to set a global variable that stores the current image index, then update the background image if it's different.

var cur_image_index = 0;
function switchImages() {
    var index = Math.floor($(window).scrollTop() / per);
    if(index != cur_image_index){
        $('body').css({
            backgroundImage: 'url(' + imgs[index].src + ')'
        });
        cur_image_index = index;
    }
}

$(window).scroll(function () {
    switchImages();
});

Here's a modified JSFiddle: http://jsfiddle.net/SEt53/1/

Note: I couldn't test it with the supplied code as the images aren't available.

Update

Even further modified to use placeholder images illustrating the goal of the script -- no lag here: http://jsfiddle.net/SEt53/3/

Brian Poole
  • 701
  • 3
  • 11
  • Oh, but its still flickering on firefox – Dennis Dec 12 '13 at 19:19
  • Can you post a link to where you're still experiencing the problem? I tested my implementation in Firefox on Win 7 and didn't experience any flickering. If you changed the code on your end, make sure to refresh your cache. – Brian Poole Dec 12 '13 at 19:55
  • After seeing how you're using the images, you may be better off using a sprite then adjusting the position of the background image as the user scrolls instead of replacing the image. Here's an answer that seems relevant: http://stackoverflow.com/a/901699/2620930 – Brian Poole Dec 12 '13 at 20:27
  • On a side note, the page looks really good but it has managed to eat up a good portion of my computer's resources on both Firefox and Chrome (Win 7). Something could definitely be optimized but it's hard to tell what as it's crashing my browser ;). – Brian Poole Dec 12 '13 at 20:29
  • hmm you have no idea what i have to do? :/ and sorry for crashing your browser !! – Dennis Dec 12 '13 at 20:31
  • Well, like I said, if you put all of the individual background images into one VERY large image (sprite) where they're stacked vertically you can just adjust the background position of the sprite as the user scrolls. – Brian Poole Dec 12 '13 at 21:33