ETag vs webpack's hash

2019-08-26 05:14发布

问题:

we're reworking our whole assets building process to use 100% webpack. In the course of this I'd like to use its hash feature (e.g. [name].[chunkhash].js) to improve caching.

But my backend colleagues say no need and we should use ETags instead for the caching. So no hash at all in the filenames.

I like the idea but I'm wondering why do the bundler offer this hash feature if ETags can be used instead.

Does anyone have experience with ETags and knows the pro/cons? (we're using a custom PHP backend btw)

回答1:

Your two proposed solutions are quite different.

By using a unique filename you can set the resource to never expire. It will be cached forever. Even more importantly, your code won't break, since your HTML is pointing only to the specific, versioned asset that it relies upon.

ETags, by contrast, are used for conditional revalidation. They are used when a resource has exceeded its cache time and the browser wants to check if the current version is still valid. So the cache time will be finite, and the browser will be forced to frequently check in with the server. More significantly, your site can break if you serve a page that relies on the new version of the asset while the old version of the asset is still cached.

So using ETags for this means you have a tradeoff between performance and correctness, and in any case the result will be strictly worse than giving the asset a unique name.