Website caching is a technique of “taking a snapshot” of your web page and storing that as html. This snapshot is then stored and given to the next visitor.
Why cache anything?
Web pages written in modern programming languages are usually compiled by the server on each request by a visitor. This means the server takes the instructions given on the page to render HTML.
Rendering web pages puts a strain on a web server, and it does this for each unique visitor. This can cause the server to appear slow, as it’s working overtime trying to provide each visitor with the page they want to see.
If we enable caching, we can “save” the first rendered copy of the HTML and then serve that straight away to subsequent visitors.
This will be quicker for the user, as rendering web pages does take time, and also put much less strain on the server.
Caching is used when the content of the page would not have changed from visitor to visitor, but what happens when the page would differ on the next load?
Any page which is unique to each visitor, such as for example “My Settings”, is not suitable for caching. We definitely don’t want to present other users with the cached version of someone else’s personal preference page.
Another instance is if the content of the page changes. If a blog article is edited, then the cached version would no longer be relevant because it doesn’t provide the next user with the up-to-date information.
Fortunately, intelligent caching systems exist to circumvent this issue. If a page renders HTML based on a set of data and that is then cached, any data changes would invalidate that cache. This way, cached versions are only served if still relevant. Similar to changing the ingredients of a recipe results in a different flavour, changing the data for a page results in different HTML and therefore you have a different recipe – you can throw the old one out.
Cache files are usually also given a “time to live”. We give a cache a time to live which we expect it will still be relevant and necessary, and then once that time has passed it is no longer used.