ServiceWorker is available in Chrome 40 beta: http://bit.ly/1Dezucl
- this is huge, and it will have a huge (positive) impact on how we build apps on the web! That said, I have a squabble with a claim that is often included alongside many ServiceWorker pitches..."Besides enabling a rich offline experience, developers can also use the API to achieve dramatic performance improvements by caching UI and other common resources between page loads."
That is a true statement, but also a slightly misleading one, since the claim and the video (youtu.be/px-J9Ghvcx4
) that's supposed to illustrate the said benefit is also achievable without ServiceWorker.
Let's unpack what's happening:
The page load consists of the following sequence: (1) user initiates a navigation to some URL, (2) UA checks if the requested document is in cache and returns that if available, otherwise it initiates a network fetch, (3) UA begins parsing the response once the bytes are available... subresource fetches are initiated, and so on.
So, how does the ServiceWorker make things faster? Well, the claim is that with SW you can cache the "shell" of the page locally and get that rendered as soon as possible (no need to block on a network fetch), and then progressively fill in the dynamic content by making other fetches and/or pulling responses from cache.
All of that makes perfect sense, except... you can get the same performance improvement by leveraging the existing HTTP cache!
If you make your HTML shell cacheable (i.e. good ol' Cache-Control
header ), it will also be returned immediately and the browser will render the page shell just as quickly. From there, your JS code would kick in and fetch the dynamic content... and repeat all the same processing steps as described previously. For bonus points, you should also ensure that other resources are cacheable as well to further improve performance.
The real difference here is that ServiceWorker will push you towards this implementation pattern
. In order to provide offline capability you will have to: make the shell cacheable; think about how to handle cases where network may not be available (or just really slow); have a strategy for working with stale data, and so on. This is not a minor tweak, this requires a ground-up rethink about how we design and deliver our apps... but the benefit is worth it.
That said, you also don't need ServiceWorker to get the claimed performance benefits (modulo actual offline mode): apply appropriate Cache-Control
policies to your assets, and you're good to go. As a bonus, this strategy will work in every existing browser - yes, even IE6! This is content caching 101 - nothing more, nothing less.tl;dr: make your "shell" HTML cacheable to get it visible ASAP, fetch dynamic content to fill in the placeholder bits from there. SW is useful but not necessary to achieve the claimed performance benefits... and once you're there, do add the SW logic to enable offline use!