When developing a WordPress theme, one of the things we have to care about is the Google Page Speed, a powerful tool capable to analyze a web page and offer tips and suggestions about how to improve load times and stuff (do you know you can also use it in localhost?). In this article we will talk about how to solve one of the possible problems: serve static assets with an efficient cache policy.
But what does it actually mean, and what can we do to fix it? Let’s see.
I suggest to take a look at this page to have a better understanding of what we’re talking about.
In short: when a user visits our web page, the server can tell their browser for how long it should store the downloaded assets. For example: let’s say we serve an image without an efficient cache policy. That way, the browser wouldn’t know for how long it should store or cache that particular asset, and that will result in longer loading times in case of subsequent requests.
Viceversa, if we do specify a cache policy, the browser will know exactly how to behave, and it’s possible it will store the assets in order to load them faster next time someone visits the page.
Let’s see what to do now, and how to fix this problem.
How to serve static assets with an efficient cache policy
So, now we have to specify the cache policy for our assets. How can we do that? It’s quite simple: we have to add some code in the .htaccess file of our WordPress installation.
If we have an Apache server, we can add this code to our file:
# EXPIRES HEADER CACHING ExpiresActive On ExpiresByType image/jpg "access 1 year" ExpiresByType image/jpeg "access 1 year" ExpiresByType image/gif "access 1 year" ExpiresByType image/png "access 1 year" ExpiresByType image/svg "access 1 year" ExpiresByType text/css "access 1 month" ExpiresByType application/pdf "access 1 month" ExpiresByType application/javascript "access 1 month" ExpiresByType application/x-javascript "access 1 month" ExpiresByType application/x-shockwave-flash "access 1 month" ExpiresByType image/x-icon "access 1 year" ExpiresDefault "access 2 days" # END EXPIRES HEADER CACHING
We can do it in two ways:
- Manually editing the file (of course it’s not recommended, and quite useless, if we’re developing a WordPress theme for other people to use);
- Following the method we already talked about here.
This should give browsers enough informations about our assets, and tells them for how long they should cache them.