Preload background images

Hi.

I have CSS background images animation on various pages of my sage9 site. However, as the images are numerous (over 10) and displayed on page load, I need to preload them as currently they flicker on pageload - due to the page loading quicker than all the images…

So I have the following code inside routes/contact.js for example (require.context gets the filenames of the images for all the images in a path) -

import { importAll } from ‘scripts/import’;

export default {
init() {
importAll(require.context(’…/…/images/astronaut’, false, /.(png|jpe?g|svg)$/));
},
finalize() {
},
};

And then in import.js I have -

export const importAll = function(r) {
let images = {};
r.keys().map((item, index) => {
images[index] = new Image()
images[index].src = r(item);
});
return images;
}

So this code is definitely running when I load the page, but it seems that it is not running soon enough to make the flickering stop. Is there are a way to guarantee it runs earlier during page load or is there a better approach to achieve the same effect (perhaps using a webpack plugin or something)?

nb. i was running the soil plugin previously but i have currently deactivated it in case it was conflicting with what I am trying to achieve.

cheers

If this becomes of interest to anyone, I gave up on this idea and used CSS sprites instead. Can post how if anyone needs it at some point.