How can I speed up the loading of the background image for my website?

Viewed 3389

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. Chrome DevTools Network Waterfall

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?

1 Answers

Since you have 5 random images, an easy way is to use CSS and make them background of any element with 0 size. This will force the browser to load the image before reaching the JS script. Of course, the CSS need to be loaded before your JS and as soon as possible.

So your code can be something like this:

html {
  background-image:
    url("img/bg1.jpg"),
    url("img/bg2.jpg"),
    url("img/bg3.jpg"),
    url("img/bg4.jpg"),
    url("img/bg5.jpg");
  background-size:0 0;
}
Related