CrowderSoup
CrowderSoup

Reputation: 164

Minify CSS on the fly: leveraging browser caching

I'm writing a script that will combine and minify requested CSS files and then echo them out. I have most of the work done, however I'm stuck on one small, yet very important piece: Leveraging browser caching.

Most visitors to ours sites are new, and rarely ever come back. So really what we're worried about is caching between page requests in the same session. Like, they hit our main page and then navigate to a few other pages and leave.

The problem I'm having is that I'm storing a timestamp in the session for the last request time for each specific set of files. So if I want main.css and internet.css this request and then main.css and phone.css next page view then the timestamp of the last request will be updated, but if I requested the same set of files again, the timestamp would be unchanged from last time.

Hopefully I'm making sense. The issue is that when a file is unchanged from last request to this one, I return 304 not modified. However, the browser is not caching the css like it should. Any ideas as to why not?

You can take a look at my code here: https://gist.github.com/4235836 (I would normally put it here, but it's kinda long)

Upvotes: 0

Views: 642

Answers (1)

sroes
sroes

Reputation: 15053

I think you should check the request header If-modified-since before sending out a 304:

if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && 
    strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $minifier->lastModified)
{
    header('HTTP/1.0 304 Not Modified');
    exit;
}

Also notice the exit. If your sending out a 304, it means the client already has the latest version, so you should exit your script there.

Edit:

When using expire headers, the browser will assume it already has the latest version. So it wont even make a request to the server, unlike using the HTTP_IF_MODIFIED_SINCE header.

So you might also want to add:

header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60 * 24)));

Then to make sure it will request a new version once the file has changed, you can do sonething like:

<link rel="stylesheet" type="text/css" 
    href="minify.php?v=<?php echo filemtime($theFileToMinify) ?>">

Upvotes: 1

Related Questions