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 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 website, the web browser needs to download all the resources server by the website from the server. These files include HTML files, CSS file, JS files, text, images and any other resources) in order to load and the display the current web page. Now, rather than actually downloading the same resources over and over again each time you visit a different page on the same website, the browser uses what is called a Web Cache. The is featured used in browsers to ‘temporarily store’ or ‘cache’ web page resources on the device's local storage. This storage or data is called ‘ Web Cache’ or ‘HTTP Cache‘.

The beauty of this function is that when a user visits the same website again, or a different page one the same website, the browser will use the copy of the resources which is currently residing in the temporary cache - rather than having to download the resources all over again. The browser will only download the resources which are different. As many website 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 bandwdith consumption by your web server and also reduces the load on the server.

Now, what does leverage browser caching 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 website 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 website's visitors.

By extending the caching lifetime (or how long a file takes to become old), you are making sure that your visitors do not spend time downloading the same files everytime they visit your website.

This change involves very little changes and is not very complicated - 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 caching period of a particular file or type of file. The ETag is then used to verify and 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 resources 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 time which you expect to change these resources. 

Change .htaccess to leverage browser caching in WordPress

To set the expiry time of files 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.

As a bare minimum, you add the following in your .htaccess file. 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.

<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
  ExpiresDefault "access plus 1 seconds"
  ExpiresByType text/html "access plus 600 seconds"
  ExpiresByType application/xhtml+xml "access plus 600 seconds"
  ExpiresByType text/css "access plus 1 month"
  ExpiresByType text/javascript "access plus 1 month "
  ExpiresByType application/javascript "access plus 1 month"
  ExpiresByType application/x-javascript "access plus 1 month"
  ExpiresByType image/x-icon "access plus 1 year"
  ExpiresByType image/jpeg "access plus 1 year"
  ExpiresByType image/png "access plus 1 year"
  ExpiresByType image/gif "access plus 1 year"
</IfModule>

We are setting files which refresh quickly such as the HTML of your site 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 site again within a month, they don't need to redownload your CSS and JS files again. If you know that you rarely perform these types of changes on your site - you can see 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 change to a long browser caching expiry

As you can also see in our example above, our image files are set to expire only once a year. This makes sure that the files which take the most time to download are kept on the visitors' machine, and won't have to be downloaded again next year. Due to this change in your .htaccess file, 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.

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 file, 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> Header append Cache-Control "public" </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 server 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 website, 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 caching through the Cache-Control headers, the ETags are no longer necessary - so we'll switch them off. Add this to in .htaccess file 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 file can actually break your site. If you make a small mistake, your server won't be able to parse the file, will start throwing blank pages, or throw error 500 and the site will be dead!

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 site faster will be doing most of these settings in the background. 

Essentially, besides handling all of the settings to leverage browser caching WordPress, these will be able to perform a number of other caching optimizations, such as creating tempory files (file cache), database optimizations, memcache and other optimizations which make your website 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
  • 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 image files 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 of files and combining them to deliver them faster to the end-user
  • Defer JS loading - such that the page renders quickly intead of waiting for all the files to download
  • Integrates and enables a CDN - such that your heavier resources are 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 server optimizations and infrastructure, 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 tying 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 it's 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 site.

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 PDF files to expire after 30 days. You can add more file extensions to customize the expiration and browser caching different for other files.

Caching 3rd party resources

While is 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.

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 and resources, unfortunately, so we strongly advise you to use the MINIMUM 3rd party scripts possible. If you can live without the script, eliminate from your website, because by including it, it will be dragging the loading time of your site down.

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

Download the list of 101 WordPress tricks every blogger should know

101 WordPress tricks

Click here to Download Now

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

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 :-)

New! DIVI 3.1 WordPress Template + PageBuilder

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

Get an exclusive 20% OFF for CollectiveRay visitors until

Divi 3

 

The Outstanding HungryJPEG Bundles

AWESOMENESS! Bundles of premium font + graphic packs at more than 96% OFF!  Get this bundle for just $29 - This month ONLY!

The Hungry JPEG Awesome font bundles

 

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.

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