Search code examples
cache-controllighthouse

Lighthouse: Fix assets with an efficient cache policy


I am trying to improve the performance of my website, and I saw that I must use an efficient cache policy. Does this mean that when the user enters the website, the website can be stored on their machine, increasing the page loading time, using a cache timeout?

I don't know if I should configure this in the website's meta tags or on the server, I use the following meta tags on my website:

<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="Expires" content="-1" />

I believe that I am not using cache on my website, which is why Lighthouse is reporting? So, what can I do to solve this, change something on the server or in the meta tag? I need an efficient answer My server is Nginx and I don't use any cache policies on my server.

Picture of Lighthouse

enter image description here


Solution

  • This recommendation is shown when you do not cache "static" files such as CSS, images, JS for at least 6 months (and ideally a year).

    At the moment the meta tags you show are saying "do not cache this page" so every time someone arrives at the page it will be served from your server and not from their local machine.

    This is fine for the page itself if it is likely to change often but for things like your site CSS and JS that is going to hurt performance.

    This answer on Nginx static files config should help you with the base config settings.

    However 30 days is not sufficient so you will need to change that to 365 days.

    It has been a while since I have had to do this but I believe the following would work (not tested)

    location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
        expires 365d;
        add_header Vary Accept-Encoding;
        access_log off;
    }
    

    Doing it via config is far better as you can decide if files that are updated often can be cached for less time (the cache length is a recommendation not something that affects your score. Set the cache as high as you can without painting yourself into a corner on files that update regularly.)

    Yet again it has been a while but I believe the file is located at "/etc/nginx/sites-available/default" but I could be wrong there, hopefully someone who is more familiar with Nginx will be able to confirm or correct me on those points.

    To test it simply update the file, then open developer tools on the site and head over to the "Network" tab. Reload the page and find a CSS file, image, JS file etc. and then check the cache-control headers for them. They should have a max age of 365 days equivalent ( max-age=31536000 is one year) as a minimum.