Advertisement
welemskicms-logo-slider

Optimize page load by enforcing cache

Make pages load faster and prevent heavy resource requests by enforcing clients to cache resources: Media, css, javascripts etc.

 There are different options to optimize your site. What I'm about to show you is how to enforce client browser to cahe resources.

For typical resources such as Images, stylesheets and javascripts, you can simply define and instruction to enforce cache using .htaccess file.

Enforce cache using .htaccess file:

<ifModule mod_headers.c>
    # Turn on Expires and set default expires to 1 hour
    ExpiresActive On
    ExpiresDefault A3600

    # Set up caching on media files for 1 hour
    <filesMatch ".(ico|gif|jpg|jpeg|png|flv|pdf|swf|mov|mp3|wmv|ppt)$">
        ExpiresDefault A3600
        Header append Cache-Control "public"
    </filesMatch>

    # Set up 1 Hour caching on commonly updated files
    <filesMatch ".(xml|txt|html|js|css)$">
        ExpiresDefault A3600
        Header append Cache-Control "private, must-revalidate"
    </filesMatch>

    <filesMatch ".(php|cgi|pl|htm|html)$">
	Header unset Pragma
    </filesMatch>
</ifModule>

 

The above snippet will only work on your static resources. Those resources such as images, css and js files that resides on your site are normally being served by the web server. However, if you have other resources that are not being served normaly you will need to use HTTP headers.

If you have images that are being served through PHP, everytime the page loads, it will always ask the server for that particular file. Your page will take time to load as the file being served, will always be handled by PHP through som I/O operations.

To enforce cache using PHP, you must add header informations such as etag and "last modified". You must also check if the images being requested are not modified and respond to the request as not modified. This will instruct web browsers to use cache if available.

Enforce cache using PHP

$tsstring = gmdate('D, d M Y H:i:s ', $timestamp) . 'GMT';
$etag = $language . $timestamp;

$if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false;
$if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? $_SERVER['HTTP_IF_NONE_MATCH'] : false;
if ((($if_none_match && $if_none_match == $etag) || (!$if_none_match)) &&
    ($if_modified_since && $if_modified_since == $tsstring))
{
    header('HTTP/1.1 304 Not Modified');
    exit();
}
else
{
    header("Last-Modified: $tsstring");
    header("ETag: \"{$etag}\"");
    
    // Do your file serving here.
}

 

Above is a bit tad messy. However, if you used a framework please consult their documentations as they have provided an easy way. Below is an example on how to do the same above but using CakePHP 3.

Enforce cache using CakePHP 3

$etag           = md5_file($filePath);
$lastModified	= gmdate('D, d M Y H:i:s', filemtime($filePath)) . ' GMT';
$lastAccess	= fileatime($filePath);

$this->response->cache($lastAccess,'+45 days'); // You can actually remove this line
$this->response->etag($etag);
$this->response->modified($lastModified);
$this->response->header(['Cache-Control' => 'private,max-age=3888000']);
		
$notModified = $this->response->checkNotModified($this->request);
if(!$notModified){
    $this->response->file($filePath);
}
		
return $this->response;

 

Below as a performace screenshot I took using firebug. Note that I was monitoring performance to one of my page with at least 50 images being served though PHP.


 

As you can see from an empty cache, it took 277 seconds to load. However, after caching the page took 5.74 seconds.

It really is important to cache resources not only it will make your page load faster, it will also prevent heavy requests to and from your web server.

Also take note that for all images being served through PHP, you have to manually instruct the client browser to cache by modifying headers. You can read the PHP's header manual to know what other stuffs you can do with headers.

Comments

Advertisement