2

My application minifies and combines static content such as CSS / JavaScript on the fly to reduce loading times for the end user. This process, is however, quite resource demanding. Due to this, I've implemented a caching system. Normally in a live enviroment, this static content rarely changes.

Would it be stupid to set the cache duration for this content to as much as one week, or even more? And then provide the admin a tool to manually clear the cache when he edits the styles and such.

An edit to make the tags more appropriate would be appreciated.

Zar
  • 6,786
  • 8
  • 54
  • 76
  • You're talking of a server-side cache, isn't it? Because you can't clear the cache of clients (though you can make them download another file if the name or a param isn't the same anymore). – FelipeAls Jun 21 '12 at 17:08
  • @FelipeAlsacreations Exactly, server-side, NOT client-side. – Zar Jun 22 '12 at 00:02

3 Answers3

1

In a server side situation, a duration after which your cache gets invalidated is too simplified in my opinion. You can know when your files are updated and you need to rebuild your cache. If the edits are made via some custom interface as part of your app, it's simple: just delete the cache if any edit is made.

But even if your admin updates the files via FTP you can look at the timestamps.

Example:

<?php
$files = array("reset.css", "style.css");

$timestamps = "";
foreach( $files as $file ){
    $timestamps .= filemtime($file);
}
$cache_file = md5($timestamps).".css";

if( !file_exists($cache_file) ){
    // Build minified version into cache file
    // (leaving the implementation out here)
    concat_and_minify($files, $cache_file);
}

echo '<link rel="stylesheet" type="text/css" href="' . $cache_file . '"/>'; ?>

This will only rebuild your minified version if any of the files change. Reading the mtime of every file is a small overhead in comparison to a "dumb" duration mechanism, but is worth the gain in flexibility.

pixelistik
  • 7,541
  • 3
  • 32
  • 42
0

A one week cache for static content seems pretty standard. Could you not have the process which writes these files also affect the caching? (e.g. rewrite an .htaccess file) depends on how you are caching.

Ingmar Boddington
  • 3,440
  • 19
  • 38
0

You can add a version to the script/style URLs, for example http://example.com/generate-styles.php?version=123. Depending on caching strategies for your HTML, this may allow you to make the CSS/JS cache much more long-living. Another approach is utilised by MediaWiki, the software used by Wikipedia: it includes a bootstrap script with a lifetime of 5 minutes that contains versions of all CSS/JS then uses this information for loading the latest versions of files (using the same trick with versioned URLs).

MaxSem
  • 3,457
  • 21
  • 34