I am working on a moving image on scroll which works.
The problem is that the images flicker as they are being downloaded every time they are changed (I checked the network tab of different browsers). The Cache-Control and expiry of the images have been set (to one day) and the images are all pre loaded with JS. It seemed to be working on Safari but because it did not on chrome, I added the cache control and expiry, and now it flickers on Safari as well.
I am out of solutions, please let me know if there is something that I would be missing!
Code to pre-load images (JavaScript):
function preloadImages(srcs) {
function loadImage(src) {
return new $.Deferred(function(def) {
var img = new Image();
img.onload = function() {
def.resolve(img);
};
img.onerror = img.onabort = function() {
def.reject(src);
};
img.src = src;
}).promise();
}
var promises = [];
for (var i = 0; i < srcs.length; i++) {
promises.push(loadImage(srcs[i]));
}
return $.when.apply($, promises).then(function() {
// return results as a simple array rather than as separate arguments
return Array.prototype.slice.call(arguments);
});
}
var imgDownloaded = false;
preloadImages(genomicsImg).then(function(imgs) {
// all images are loaded now and in the array imgs
imgDownloaded = true;
$(".moving-image-container").css('animation', 'none');
$('#moving-image-container-loading').fadeOut();
$('html').css({
overflow: 'auto',
height: '100%'
});
}, function(errImg) {
// at least one image failed to load
});
Code to change image:
function trackScrollPosition() {
const y = window.scrollY - 75;
const label = Math.max(Math.min(Math.floor(y/10) + 3, 144), 0);
const imageToUse = genomicsImg[label];
// Change the background image
$('.moving-image-container').css('background-image', `url('${imageToUse}')`);
}
$(document).ready(()=>{
$(window).scroll(()=>{
if (imgDownloaded == true) {
trackScrollPosition();
}
})
})