Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flicker on jQuery Background Change

I created a jsfiddle for my current code. http://jsfiddle.net/gL5sB/38/

I am trying to change the body background css on scroll event. When the background changes it appears to flicker when the css is updated and new image is loaded. At times it seems smooth and then it seems to get worse. Very strange. Curious if anyone knows how to optimize?

I am preloading the images. Not sure why the flicker. Any ideas?

$(document).ready(function () {
    switchImage();
});

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

var pics = []; // CREATE PICS ARRAY

//PRELOAD FUNCTION TO SET UP PICS ARRAY IN MEMORY USING IMAGE OBJECT
function preload() {
    for (i = 0; i < arguments.length; i++) {
        pics[i] = new Image();
        pics[i].src = arguments[i];
        //alert("preload " + arguments[i]);
    }
}
preload(
    'bgImage/100.jpg',
    'bgImage/101.jpg',
    'bgImage/102.jpg',
    'bgImage/103.jpg',
    'bgImage/104.jpg',
    'bgImage/105.jpg',
    'bgImage/106.jpg',
    'bgImage/107.jpg',
    'bgImage/108.jpg',
    'bgImage/109.jpg',
    'bgImage/110.jpg',
    'bgImage/111.jpg',
    'bgImage/112.jpg',
    'bgImage/113.jpg'
);

function switchImage() {
    var s = $(window).scrollTop()/10;
    var index = Math.floor(s / 5);

    $('body').css('background-image', 'url(' + pics[index].src + ')');
}
like image 217
Shawn Altman Avatar asked Feb 17 '23 17:02

Shawn Altman


1 Answers

Why don't you use one image (sprite image) and just move it with background-position instead of replacing the image? (about the size - you can set percentage based background-size in your case - the height will be 1400%

Because your'e preloading all the images anyway - it won't cost you in page loading time - and it might also save some time because with the right compression 1 image of 14 will weight less then 14 images of 1

like image 88
Yaron U. Avatar answered Feb 27 '23 00:02

Yaron U.