I am serving Angular app as a static content in Express Server. When serving static files with Express, Express by default adds ETag
to the files. So, each next request will first check if ETag
is matched and if it is, it will not send files again. I know that Service Worker works similar and it tries to match the hash
. Does anyone know what is the main difference between these two approaches (caching with ETag
and caching with Service Workers), and when we should use one over the other? What would be the most efficient when it comes to performance:
To give a better perspective, I'll address a third cache option as well, to clarify the differences.
Basically we have 3 possible layers of caching, based on the priority they are checked from the client:
PS: Some browser like Chrome have an extra memory cache layer in front of the service worker cache.
The service worker is the most reliable from the client-side ones, since it defines its own rules over how to manage the caching, and provide extra capabilities and fine-grained control over exactly what is cached and how caching is done.
The Browser caching is defined based on some HTTP headers from the assets response (Cache-Control
and Expires
), but the main issue is that there are many conditions in which those are ignored.
For instance, I've heard that for files bigger than 25Mb, normally they are not cached, specially on mobile, where the memory is limited (I believe it's getting even more strict lately, due to the increase in mobile usage).
So between those 2 options, I'd always chose the Service Worker cache for more reliability.
Now, talking to the 3rd option, the CDN checks the HTTP headers to look for ETag for busting the cache. The idea of the Server-side caching is to only call the origin server in case the asset is not found on the CDN.
Now, between 1st and 3rd, the main difference is that Service Workers works best for Slow / failing network connections and offline, since the cache is done client-side, so if the network is off, then the service worker retrieves the last cached information, allowing for a smooth user experience. Server-side, on the other hand, only works when we are able to reach the server, but at the same time, the caching happens out of user's device, saving local space, and reducing the application memory consumption.
So as you see, there's no right / wrong answers, just what works best for your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With