I am currently implementing a fading background image effect on my web page, where the current image fades out as the next one fades in. Here is my code:
var backgrounds = [];
backgrounds[0] = './img/bg.jpg';
backgrounds[1] = './img/bg2.jpg';
backgrounds[2] = './img/bg3.jpg';
function changeBackground() {
currentBackground++;
if(currentBackground > backgrounds.length-1) currentBackground = 0;
$('.bgContainer').fadeOut(1500,function() {
$('.bgContainer').attr('src', backgrounds[currentBackground]);
$('.bgContainer').fadeIn(3000);
});
setTimeout(changeBackground, 5000);
}
The functionality is working well, but I have noticed that each time the image fades in, other elements on the page start dropping frames and become laggy. Is there a way to optimize this to reduce frame drops?
.bgContainer{
position:fixed;
z-index: -1;
width:100vw;
height:100%;
top:0;
}
<img class="bgContainer" src="./img/bg.jpg">