Hi there,
I’ve recently built a script that is meant to preload a selection of image references and push them into an array, for a function to cycle through every 300ms and display within an HTML element with the ID “animation”. Note that this animation is only meant to run on device widths higher than 991px, ie. tablet and above.
Unfortunately what appears to be happening is the images aren’t being preloaded and instead are being loaded on each frame change, thus causing a big lag as shown below using the Chrome DevTools Network tab.
Below is the code that I have so far:
$(window).on('load', function () {
var window = $(window);
function checkWindowWidth() {
var clientWidth = $("body").prop("clientWidth");
var picPaths = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
var curPic = -1;
//preload the images for smooth animation
var imgO = new Array();
for (i = 0; i < picPaths.length; i++) {
imgO[i] = new Image();
imgO[i].src = picPaths[i];
}
function swapImage() {
curPic = (++curPic > picPaths.length - 1) ? 0 : curPic;
imgCont.src = imgO[curPic].src;
setTimeout(swapImage, 300);
}
imgCont = document.getElementById('animation');
// If 975+= (991 - scrollbar), animate background images
if (clientWidth >= 975) {
swapImage();
}
}
// Execute on load
checkWindowWidth();
});
Thanks in advance!