Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice to manage all asset caching (images, css, js, everything)

I'm working on a moderately-sized web application and trying to come up with the best solution to make all browsers use the cache and only invalidate it when there is an update to the asset being loaded.

According to the research I've done here and elsewhere, everyone seems to be in agreement that appending a ?v={version#} to an asset such as a css or js file is a great way to automatically invalidate the cache when an asset is updated. (As per Force browser to clear cache and Better way to prevent browser caching of JavaScript files)

But it seems to me that this solution should be generalized to all assets that reside on a web server.

So my question is, would it be a good practice to have a build script look through each src="" attribute across the entire website -- whether img, css, or js, and programmatically append ?={timestamp} where timestamp is the time when the file is last modified. This way whenever you push from dev to staging to production, only those files that have been modified will have a changed time stamp, and the browser will know to invalidate the cache for those files.

Any flaws with that approach?

NOTE: Thinking this over a bit more, timestamp would definitely be undesirable in the case of changes that are later reverted. Therefore, appending ?={md5(filecontents)} is a more robust approach. Nevertheless, the question about whether implementing this across all assets and all builds still stands.

like image 467
Peter Thorpe Avatar asked Jul 21 '13 23:07

Peter Thorpe


1 Answers

Found what I believe to be an acceptable solution at How to force browser to reload cached CSS/JS files? No idea how I missed this in my original investigation.

For anyone who comes to this question, note I'm referring to the first answer on the linked page that references Google's mod_pagespeed plugin for apache. This works at the web server level, thus "[it works] with PHP, rails, python, static HTML -- anything."

This is precisely the kind of solution I was looking for. This tool, or something similar, should be in use by all web developers to keep caching logic orthogonal to the code itself.

like image 87
Peter Thorpe Avatar answered Nov 10 '22 23:11

Peter Thorpe