Browser caching

Browser caching is based on the idea that it is not necessary to fetch all the files included in a response if some of these are exactly the same over a certain period of time. The way it works is through headers that are sent by the server to the browser in order to instruct it to avoid getting certain pages or files within a certain timeframe. Thus, the browser will display content kept within its cache rather than fetching the resources over the network within the span of that certain period of time, or until the resource changes.

Thus, browser caching relies on cache-control evaluation (expiration model) and response validation (validation model). Cache-control evaluation is defined as a set of directives that inform the browser of who can cache the response, under what circumstances and for how long. Response validation relies on a hash token in order to determine if the content of a response has changed or not. It also makes it possible for the browser to avoid fetching the results again even if cache-control indicates that the cached content has expired. In fact, upon receiving the response from the server indicating that the content has not been modified, based on the fact that the sent token has not changed on the server, the browser simply renews the cache-control and resets the time delay before expiration.

This is accomplished through the use of certain response headers. These are Cache-Control and ETag headers. Here is an example of these received headers within a response:

How browser caching works

In this example, Cache-Control indicates a max-age of 120 seconds and sets an ETag with value "e4563ff". With these two headers, the browser will be able to manage its cache adequately. Thus, enabling browser caching is as easy as adding those response headers to the responses returned by the web server. In the case of Apache, it is a simple question of making sure that the FileETag directive was added to the server's configuration file.

It is also possible to set the Cache-Control and Expires headers directly using the Symfony framework in PHP. Specifically, Symfony's response object allows you to set all Cache-Control headers using its setCache() method. Here is an example when using this method:

# src/Controller/SomeController.php

...

class SomeController extends Controller
{
public function indexAction()
{
$response = $this->render('index.html.twig');

$response->setCache(array(
'etag' => $etag,
'last_modified' => $date,
'max_age' => 10,
's_maxage' => 10,
'public' => true,
// 'private' => true,
));

return $response;
}
}

Having seen how easy and simple it is to start using browser HTTP caching, let's take the time to see how HTTP caching has other benefits to offer when combined with a technology such as HTTP Reverse Proxy server technology.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset