Best Practice to manage all asset caching (images,

2019-03-18 06:03发布

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.

1条回答
混吃等死
2楼-- · 2019-03-18 06:04

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.

查看更多
登录 后发表回答