Hacker News new | ask | show | jobs
by Kiro 2961 days ago
Stupid question but what does the Service Worker actually do? I thought they were used for offloading work to another thread but nowadays I always see it used for "offline mode". Why can't you just solve it with caching? Feels like I misunderstand something.
3 comments

You are probably mistaken SW for Web Workers.

Web Workers are used to offload work to another thread and can communicate with messages

Service Workers is a new API which is now supported by all major browsers.

SW is branded as: Rich offline experiences, periodic background syncs, push notifications and more. "A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don't need a web page or user interaction."

Full article on this topic: https://developers.google.com/web/fundamentals/primers/servi...

As others have commented, you're thinking of WebWorkers, whereas ServiceWorkers are quite a new, and separate thing.

The way I've (over?)simplified explaining ServiceWorkers to people is that they're like a proxy application running between your browser tab and the actual web service (server).

They can see/intercept/manipulate requests and responses, and have their own cache. This obviously enables offline mode (the request goes through the ServiceWorker and can be responded to without contacting the web if there's a cache), but also potentially quite a few other features and ideas.

The precursor to Service Worker is AppCache, purely a manifest that described how to cache things. It worked for the basic cases like SPA's, but feel apart when dealing with dynamic content.

Obviously this could all be solved by applications loading their content via a javascript cache, but then you are putting a hard dependency on javascript, service workers allow you do do the age old <img src="profile.jpg" its going to work in all the browsers, but if your browser supports service workers it can upgrade that <img src=" to load data from cache when offline

tl;dr service workers allow you to add dynamic caching to existing web content via progressive enhancement