Leverage browser caching WordPress

One of the most easy ways to make your WordPress website faster - which involves no effort at all from your side, is to leverage browser caching in WordPress. This is one of the high priority tasks recommended by Google to make your website load faster. It is also recommended by sites such as GTMetrix or Google Pagespeed Insights to make your site faster. 

 

What is Browser Caching?

Before we actually show you how to implement this, we are first going to discuss what leverage browser caching in WordPress means and how it works?

Once we explain how it works, you can understand how it helps to make your pages load faster

Essentially, when somebody visits a page, the browser needs to download all the resources server on that domain from the server. These include HTML, CSS file, JS, text, images and any other assets) in order to load and display the current page. Now, rather than actually downloading everything over and over again each time you visit a different page on the same site, the browser uses what is called a Web Cache. This is a feature used by browsers to ‘temporarily store’ or ‘cache’ web page assets on the device's local storage. This storage or data is called ‘ Web Cache’ or ‘HTTP Cache‘.

Have a look at this fun diagram which explains how the web cache works:

web cache diagram

We can see above, that the first time the user device (left) asks the server (right) for the images/logo file, the request is intercepted by the web cache (which checks whether it has a copy of that file). If it doesn't, it fetches it from the server. On the next visit, instead of going to the server, it gets it from its own copy.

So, the beauty of this function is that when a user visits the same site again, or a different page on the same domain, the browser will use the copy which is currently residing in the temporary cache - rather than having to download the resources all over again. The browser will only download anything which is different. As many websites will only have minimal changes from one page to another and between visits, reusing the cached copy enabled the page to load much much faster.

This also helps reduce the bandwidth consumption by your webserver and also reduces the load on the server. You might also have encountered a warning when optimizing your pages for speed.

Leverage browser caching warning

Sites such as GTMetrix can show the following leverage browser caching warning, which you'll need to fix if you haven't activated the settings below.

Warning on Google Pagespeed Insights

Now, what does this actually mean?

Although the above-described function is great in theory, by default most websites will "mark" the content to expire after 8 days or a short period of time. What this means is that if a user visits your domain again after 1 week, they will need to download the resources all over again.

By leveraging browser caching, what we actually do is instruct the browser to extend the lifetime or expiry date of the resources which are downloaded by our visitors and consequently optimize performance.

By extending the lifetime of the cache(or how long a file takes to become old), you are making sure that your visitors do not need to wait to download the same things everytime they visit your site.

This involves very little changes and is not very complicated to implement - and you'll find the exact syntax below.

What the change actually does, is set content expiry dates by adding Cache-Control Headers and ETag Headers in HTTP headers. The Cache-Control header declares the cache period of a particular file or type of file. The ETag is then used to verify any changes which exist (or not) between the cached and requested resources.

The setting typically allows you to the specific the period in days, months or years to store the cache locally. Of course, if you expect to change the resources every so often, it is advisable to set expiry dates with a frequency which corresponds roughly to the period when you expect to change these. 

Incidentally, if you are looking to make your WordPress fast, there are a few plugins such as this one which can make a real difference in performance in a few minutes (with little to zero effort).

Make your website faster

Not ready to use a plugin for now? Read on...

Change .htaccess to leverage browser caching in WordPress

To set the expiry time of resources such as images and CSS files, this requires a slight modification to your .htaccess file, which is found in the root of your hosting server. This is done by changing the expire headers to boost performance.

As a bare minimum, you add the following in your .htaccess. To do this, simply access your hosting CPanel, and with your File Editor, find the .htaccess file and add the following to the bottom of the file. Do not make any other changes.

#Customize expires cache start - adjust the period according to your needs
<IfModule mod_expires.c>
  FileETag MTime Size
  AddOutputFilterByType DEFLATE text/plain text/html text/xml text/css application/xml application/xhtml+xml application/rss+xml application/javascript application/x-javascript
  ExpiresActive On
  ExpiresByType text/html "access 600 seconds"
  ExpiresByType application/xhtml+xml "access 600 seconds"
  ExpiresByType text/css "access 1 month"
  ExpiresByType text/javascript "access 1 month"
  ExpiresByType text/x-javascript "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 application/pdf "access 1 month"
  ExpiresByType image/x-icon "access 1 year"
  ExpiresByType image/jpg "access 1 year"  
  ExpiresByType image/jpeg "access 1 year"
  ExpiresByType image/png "access 1 year"
  ExpiresByType image/gif "access 1 year"
  ExpiresDefault "access 1 month"
</IfModule> #Expires cache end

We are setting assets which refresh quickly such as the HTML of your page to expire after 600 seconds, whilst we are changing such things as the CSS and Javascript to only expire one a month.

This means, that if your visitor visits the page again within a month, they don't need to redownload your CSS and JS assets again. If you know that you rarely perform these types of changes on your site - you can set the value higher, to 1 year, similar to the jpeg, png expires header.

This is the most effective way to leverage browser caching for WordPress or other websites which make use of an .htaccess file.

Set Image files to a long expiry time

As you can also see in our example above, our images are set to expire only once a year.

This makes sure that the largest media which takes the most time to download are kept on the visitors' machine, and won't have to be downloaded again until the next year. Due to this change in your .htaccess, you are fully leveraging browser caching in WordPress - the images are not downloaded again for one whole year.

This makes the experience of a returning customer much more positive - because it takes less to load each page.

After you've set the expiry dates, it's important to also set the correct Cache-Control headers such that the above setting actually works correctly. This is another setting in the .htaccess, which you can find below.

Add Cache-Control Headers

The following setting should also be added to the file to set the cache-control headers as discussed above.

# BEGIN Cache-Control Headers
<IfModule mod_expires.c> <IfModule mod_headers.c> <filesMatch "\.(ico|jpe?g|png|gif|swf)$"> Header append Cache-Control "public" </filesMatch> <filesMatch "\.(css)$"> Header append Cache-Control "public" </filesMatch> <filesMatch "\.(js)$"> Header append Cache-Control "private" </filesMatch> <filesMatch "\.(x?html?|php)$"> Header append Cache-Control "private, must-revalidate" </filesMatch> </IfModule> </IfModule>

We've already set the expiry dates so we don't have to set it again here.

(Multi-server sites or CDNs) Unset ETag headers

The final thing which we need to do is (un)set the Etags setting.

Essentially, this is important only if you are using a CDN to serve some of your resources. Etags are headers that are typically constructed using attributes that make them unique to each specific machine hosting a site (technical reason - it uses an MD5 generated by the server, making it unique to the server generating it).

If a website is using a CDN or multiple servers to serve their pages, there is NO guarantee that the same server will be used - therefore the tags will not match when a browser gets the original component from one server and later tries to validate that component on a different server.

For this reason, it would be best to UNSET them if you are using multiple servers or a CDN to host your website. This allows the Cache-control headers to actually control the caching rather than the ETags. Given that we've put in settings to control the cache through the Cache-Control headers, the ETags are no longer necessary - so we'll switch them off. Add this to your .htaccess to unset them.

# Disable ETags
<IfModule mod_headers.c>
	Header unset ETag
</IfModule>
FileETag None

If you need to read more about what the Etags do, you can find more details and read about them in this article: https://en.wikipedia.org/wiki/HTTP_ETag

Leverage Browser Caching WordPress Plugin

Tweaking and playing around with the .htacess can actually break your site. If you make a small mistake, your webserver won't be able to parse it, will start throwing blank pages, or throw error 500 and the site will be dead!

300x250Orange

So if you're averse to doing this, you can install a simple plugin which takes care of handling all of this.

The plugin can be found here.

Simply, install it and activate and you're done!

Browser caching plugin

By implementing these minimal changes, you will see that your score on such sites as GTMetrix will increase significantly. 

Of course, there are plenty of other plugins which are able to do this. Most plugins which are intended to make your pages faster will be doing most of these settings in the background. 

Essentially, besides handling all of the settings to leverage browser caching in WordPress, these will be able to perform a number of other caching optimizations, such as creating temporary copies (file cache), database optimizations, memcache and other optimizations which make your site faster overall.

These would include plugins such as WPRocketWP Fastest Cache, and W3 Total Cache and premium caching plugins.

WP Rocket

This is one of fastest, most recommended plugins for WordPress which can handle all your speed optimizations with a few clicks. Essentially, this performs such speed optimizations as

  • static files compression (GZip) - to make the total size of data to be delivered smaller (we have a full tutorial on how to enable GZip compression here)
  • enables a file cache (including cache preloading) - to put less stress on the server (fetching a prerendered copy of each page)
  • Google Fonts optimization - to make sure heavier fonts are loaded quickly),
  • lazy loading - such that images are only loaded when the user scrolls down to the section of a page where the image is required
  • Minification and combination - shrinking the size and combining text assets to deliver them faster to the end-user
  • Defer JS loading - such that the page renders quickly instead of waiting for all the assets to download
  • Integrates and enables a CDN - such that your heavier media is delivered faster 
  • DNS prefetching - to reduce the time it takes to resolve the source of 3rd party content

All the above might sound like gibberish to anybody who is not involved in infrastructure optimizations, but in reality, these are all the things you need to do to make your website load faster.

The great thing is that with WP Rocket you don't have to do the heavy lifting and the configuration - it's all done for you! We highly recommend trying out this plugin, which has been rated as the best way to make your website faster.

Visit WP Rocket Now

W3 Total Cache

This is one of the most popular caching plugins ever. It's been around for a very long time and has had a lot of time to mature very nicely to embed most of the features one would expect from a caching plugin.

The problem is this. Myself, somebody who has been around WordPress and web design for a very long time, and it is such a frustrating experience working with it. The plugin is not straight-forward to set up and you really have to understand it and know it well to be able to get it up and running nicely.

If you're looking for a good way to leverage browsing caching in WordPress using a plugin, we would highly recommend WPRocket above as opposed to W3Total Cache.

Leverage Browser Caching for Nginx

If your website is actually using Nginx as its server, you will need a different code, because Nginx does not have an .htaccess file. However, it's still relatively easy to implement this, because you just need to perform a few edits in the conf file of the server.

You need to add the code below inside of an existing server block in your conf file. This will typically be in /etc/nginx/sites-enabled/default

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 365d;
    }

    location ~*  \.(pdf)$ {
        expires 30d;
    }
}

Add Cache-Control Headers for Nginx

 

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 90d;
add_header Cache-Control "public, no-transform";
}

 

As you can deduce from the code above, we're setting the expiry location for image files to 1 year or 365 days, whilst we're setting PDFs to expire after 30 days. You can add more file extensions to customize the expiration making it different for other filetypes.

Caching 3rd party resources

While it is fairly easy to apply the above setting, you'll find that even after you perform the above changes, you will still keep getting this message in website speed testing tools and Google Pagespeed Inisghts.

Caching external resources

This is because, most 3rd party scripts and services do not specify a long expiration time - for various different reasons.

You have no control over these scripts, unfortunately, so we strongly advise you to use the MINIMUM 3rd party scripts possible. If you can live without the script, eliminate it from your website. By choosing to include it, it will be dragging the loading time of your pages down.

Specify a Cache Validator

This is another warning frequently shown by GTMetrix, typically coming from 3rd party scripts. Essentially, this is the same problem we have just described in the previous section, where certain scripts do not specify either an ETag header or a Last-Modified header as described.

Unfortunately, there is not much you can do to resolve this problem, if these specific errors are coming from domains which are outside of your control such as Facebook, or in the case of the below image, Sumo - so there is nothing you can fix.

Your only solution, in this case, would be to remove these scripts from your domain completely if you want to be sure that this warning does not appear.

Specify a cache validator

Conclusion

Above we've shown you a bunch of ways to implement to make sure you are able to leverage browser caching and make sure content which is downloaded is reused over and over again. Make sure you've implemented this on your site, to stop the error from showing up on tools which analyse your site's speed metrics. 

If you're interested in making your website faster - we would highly recommend visiting our article: [21 actions] Speed up WordPress: Get a Super Fast Website Today - a complete guide.

On the other hand, if you feel that this is somewhat beyond your own capabilities, we would recommend you leave this stuff in the hands of the PROs. Our friends at WPBuffs can handle your website in three aspects (1) speed, (2) security and (3) general maintenance and upkeep. That way, you can focus on running your website, making sure your site stays up and running nicely.

Visit WPBuffs Now

One more thing... Did you know that people who share useful stuff like this post look AWESOME too? ;-)
Please leave a useful comment with your thoughts, then share this on your Facebook group(s) who would find this useful and let's reap the benefits together. Thank you for sharing and being nice!

Featured On

Inc Magazine Logo  

Sitepoint logo  

CSS Tricks logo   

webdesignerdepot logo   WPMU DEV logo   

and many more!

Where are we hosted?

This site is proudly powered by FAST VPS InMotion Servers and given an insane speed thanks to MaxCDN!

Web Hosting MaxCDN - Speed up your website

New! DIVI 3.1 WordPress Template + PageBuilder

You'll surely create a perfect website with Divi 3.1!

Get an exclusive 10% OFF for CollectiveRay visitors until

Divi 3

 

WordPress Elementor Sale

Themes for the most popular WordPress page builder from TemplateMonster!

We've got an exclusive 10% OFF for CollectiveRay visitor until - use Coupon Code: collectiveray

TemplateMonster Elementor sale

 

TemplateMonster Bundles

Awesome bundles for awesome websites. $1300 worth of products for $49 only!

We've got an exclusive 10% OFF for CollectiveRay visitors until - use Coupon Code: collectiveray

TemplateMonster Bundles

How to make your website FAST!

Step-by-step - free email course, how to make your website load in less than 1 second 

The Outstanding HungryJPEG Bundles

AWESOMENESS! Bundles of premium font + graphic packs at more than 96% OFF!  Get a bundle for just $9 - ONLY!

The Hungry JPEG Awesome font bundles

 

Advertise on CollectiveRay.com

CollectiveRay (formerly known as DART Creations) is interested in developing partnerships with mutual benefit. If you like the stuff we publish and would like to develop a relationship, we'd be happy to hear from you. Go on - drop us a line - we'd love to hear from you :-)

 

 

Disclosure: CollectiveRay is funded personally out of pure passion for helping people working with websites. We do however generate some income through recommendations of products. This means if you click on a link and purchase an item we link to, we will receive a small sum out of that sale. We usually partner with vendors to make your purchase cheaper than buying direct.

who are we?

CollectiveRay is run by David Attard - working in and around the web design niche for more than 12 years, we provide actionable tips for people who work with and on websites. We also run DronesBuy.net - a website for drone hobbyists.

David attard

Follow us on Social

Follow us on Facebook   Follow us on Google+   Subscribe to our RSS Feed   Follow us on Twitter