I am trying to improve the performance of my website. In the Chrome DevTools, I see that the request for bg2.jpg is being delayed in starting its download.
I figure this is happening because I am using JavaScript to generate the URL and set it as a background image in CSS and the Chrome browser is deprioritizing the script tag containing this code.
let bgImgName = "bg" + Math.floor(Math.random() * 5);
...
document.documentElement.style.setProperty("--bgUrl", `url(img/${bgImgName}.jpg)`);
My thought is to preload the image using, <link rel="preload" href="img/bg2.jpg" as="image">
in the HTML. My problem is that I have to hardcode the URL for this to work (because my server only runs apache and does not have a true server-side language). My server (host with GoDaddy on a Linux shared host) does give me access to the .htaccess file and there might be a way to use Server Side Includes to inject the random number, but I have not found a way to do this.
Is there a way to do it this way, or a different way to solve this problem?
Update: Looks like I cannot use Server Side Includes. I forgot that I gzip the HTML files before I upload them to the server so that there is a performance boost of serving the compressed static files right from the disk.
Is there a way I can add a random number in the .htaccess file that is passed to the browser?
img0.jpg
then randomise from there...