Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Writing a Service Worker (hacklabo.com)
227 points by kayfloriven on July 9, 2017 | hide | past | favorite | 55 comments


I always get all stoked on service workers until I remember that half my users are on safari. Then I get bummed.


I wouldn't let that stop you: adding a service work won't in any way degrade the experience of Safari users. When used for caching, it's pure progressive enhancement.

Sure, some browsers will have a more robust experience in adverse network conditions, but the experience once a page has loaded will be identical. It's also difficult to accidentally make the worker a hard dependency of a site, since even supported browsers will load the site without the worker on first visit.


I might be dumb but can't you kind of polyfill this behavior by making your SPA cache itself on load and response to everything as events, like shown in the repo linked in this article?


> I always get all stoked about creating an iOS app until I remember that half my users are on android. Then I get bummed.

But seriously it is a bummer Safari doesn't support service workers yet. It's possible higher adoption would put more pressure on Apple to add support. In the meantime it can be a great enhancement where it is supported.


What's the difference with Safari? (not a JS dev, so this is not familiar territory)


It's not just a safari problem, last I checked Chrome on iOS also does not support service workers, so you're just helping Android users.

Apple has a vested interest in pushing users towards their walled garden for apps, while Google and Mozilla are trying to bring app-like experiences to the browser. There are hints of Safari supporting serviceworkers but I'm not holding my breath.

Highly recommend Alex Russel's talk on progressive web apps as background: https://m.youtube.com/watch?v=x7cfLDFVyHo

I happen to agree that offline-readiness (via service workers) is at the core of whether the open web will continue to be a relevant medium.


> last I checked Chrome on iOS also does not support service workers, so you're just helping Android users.

All browsers on iOS are wrappers around WKWebView (Safari, for the most part). You can’t release a browser app for iOS that doesn’t use this.


> you're just helping Android users

And desktop users of Chrome, Firefox, and soon Edge (which has support implemented behind a flag).


While true, the most compelling use-case for serviceworkers is still on mobile. Serviceworkers solve the problem of intermittent connectivity. They can patch the gap when a user drops a connection for less than a few minutes (e.g. when a user is mobile).

Laptops and desktops still benefit, but less so because generally if you sit down to use one of those devices in an area of poor connectivity, you're going to run out of things you can do with your serviceworker's cached content pretty quickly. If you're developing a serviceworker, the improved experience will be most felt by mobile users.


That depends on the application. Some applications will run out of stuff to do after a few minutes offline, but others (especially where individual tasks are pretty independent, like Google Docs) can still be very useful for long periods, and can benefit from increased control of caching strategies.


Unfortunately for Edge/Windows, in order to make the app installable it will have to be registered in the Windows Store. A small nuisance, and maybe a compromise that Safari/OSX could move towards, but still a pointless exercise that misses the point of PWAs.


The Guardian has an experimental iOS app that polyfills the Service Worker API. The way you'd use it is, roughly, change the INITIAL_URL variable to your home page, change the name / icon / etc. of the app, then release it on the App Store as an actual app.

https://github.com/gdnmobilelab/hybrid

If you have an actual iOS app already, then this is of course worse, but if you have something that works nicely as a webpage on Android with ServiceWorkers and you want iOS users to have some option at all, this is probably worth playing with.


Not implemented. "Under consideration".

https://webkit.org/status/#specification-service-workers


Service workers are really cool. I love them in using it in react project. In fact, create-react-app does inject a service worker for you to cache all the static files in production environment.


What does the "Got it!" button do? Just let the author know that I understood the guide?

I really like that button. I don't know, it just drives home the point that you care that I understood your guide -- which was clear and easy to read.


Isn't that button for acknowledging the fact that the site will use cookies?


Yeah, but the color of that dialog should probably be changed. On a quick glance it blends in.


That's exactly what it is.


Why don't use HTML5 application cache with the manifest? At first look it do the same that you need:

* Cache css, js and images file

* Defined cached entries page ex index.html, show.html etc..

* Fallback Entries

and it is really simple to use. https://developer.mozilla.org/en-US/docs/Web/HTML/Using_the_...


For one, it's deprecated. I've also found (at least during development) that it seems to cache too aggressively. Plus it lets you do weird things, like cache your appcache file. Combine that with caching the HTML, and you won't even be able to update your site until you clear the browser cache. I do appreciate the surface simplicity, but the complexity under the surface makes it painful to use.


I had a project that was pretty much a perfect fit for the app cache:

    - 100% static
    - reasonable dataset size
    - amenable url space (a few static files, then a large url
      space that could fall back to serving out the index.html 
      file)
Despite this, the appcache just never worked reliably. It was a crapshoot whether it would actually work offline for any given user, I had to be careful not to permanently cache the appcache itself, and it was just generally inflexible and unpleasant.


From the top of your link: "Using the application caching feature described here is at this point highly discouraged; it’s in the process of being removed from the Web platform. Use Service Workers instead."

Also: https://alistapart.com/article/application-cache-is-a-douche...


I imagine this comes with massive overheads in regards to data and ram usage, both of which are precious commodities on mobile platforms.


At least when following this example the site should work just fine when JS is disabled, which was the main issue I had when I tried following google's (?) tutorial on how to use service workers to make webapps work offline. That one revamped the whole site into a JS app powered by service workers, with a blank white page remaining without JS. Not the case here.

I don't think this approach here should cost much performance. It is just a thread checking a cache (that will be on disk) on page load.


Ah this is really nice but still feels quite verbose (+the web standards are know for their bad documentation for end devs). A small library with good documentation making things easier could kill it, similarly to localstorage, cookies, etc.


I highly recommend using Workbox: https://workboxjs.org/.

One of the more gnarly parts of ServiceWorker is having to clean up old caches during a version change. The workbox-build module generates revision hashes for your pre-cached assets and handles any cache clean ups for you.


Best use case of this I guess, is some kind of flight mode for web apps. Before going in to metro or flight, you click a button, and for example HN caches front page for you.


More than that - service workers have background sync and stuff like that as well. Imagine a messaging app where you can read and write messages no matter what the connectivity state is, then have the phone sync when you come back online.


Exactly. I've written something like that but instead of messaging it was an issue tracker meets wiki. Completely offline with SW and IndexedDB with background sync when there was a connection. Works very well on the airplane :)


How did you make it sync in the background, by which I mean when the app is not in the foreground? That's the scary stuff of service workers.


Not scary at all. Check out this article on Background Sync [0]. It's not supported everywhere yet but the fallback to sync when the page is open is good enough. Of course you can also do sync on push events (they have broader support) but then you have to show a notification.

Service workers have access to Indexeddb but not to local storage. That's something to remember.

[0]: https://developers.google.com/web/updates/2015/12/background...


That link describes a web page that keeps running and sending data even after your browser is closed. Why shouldn't I be scared by that? Isn't that the holy grail for anyone who wants to track and surveil users?


It seems like there are some restrictions on them, but they are kind of vague about exactly how restrictive they are.

> Sync events will often complete while the user has a page open to the site, so requiring user permission would be a poor experience. Instead, we’re limiting when syncs can be registered and triggered to prevent abuse. E.g.:

> You can only register for a sync event when the user has a window open to the site.

> The event execution time is capped, so you can’t use them to ping a server every x seconds, mine bitcoins or whatever.


Caching cross-origin resources is problematic because you can't check the response code: https://stackoverflow.com/q/35626269


You can still cache the response you just don't get to see what the response was. For those types of resources it's best to only fallback to using them if the user is offline.


I was going to say, "Isn't this what the application cache is for?" then I looked and saw it has been removed from the standards.


AppCache looks like a poor hack if you want offline site that is more complex than just a static blog post. There are numerous edge cases that you can easily handle in SW's JavaScript vs AppCache's limited declarative language. For example navigation requests can be special cased. Or you can decide yourself when to make a network request vs cache lookup. AppCache used some weird rules (e.g requests with query parameters never use cache).


Here's the simple service worker ever. It just caches some URLs and load them from the cache:

https://github.com/fiatjaf/personal-graphs/blob/6182f5a40fec...


The author must not have been to Tokyo because I've never had bad connectivity underground there.


>This is, unfortunately, a familiar scene for everyone, whether you are in Tokyo, Milan or New York.

Damn it, if I'm going to have the song stuck in my head all day so should all of you!

https://www.youtube.com/watch?v=P5mtclwloEQ


How large can the cache get at max?


From my understanding, the cache, IndexedDB and other storage are all bundled together. But I think the actual max changes according to device.


It's browser specific. Most use a heuristic along the lines of allowing browser storage (inclusive of IndexedDB, etc.) to use a combined 50% of the device's otherwise free space. Usually each origin is limited to around 20% of that potential usage.


Could this be used to optionally reduce bandwidth use? For instance, could someone use this before going into Airplane Mode, even though they are in the middle of a city, but do not want to use wireless data?


Yep - that's one of the great things about service workers, IMO. The caching is pretty guaranteed, unlike the standard mobile caching which empties out far more often than you expect.


It is also useful for low-bandwidth or intermittent-bandwidth situations (i.e. poor network coverage).


yes, a site could allow the user to preload data into the cache and prefer that later.


Why the little story at the beginning? Annoying and silly.


No demo?


20 lines of JS top on HN. Slow news day I guess...


I interpreted the title to be a story from a programmer creating software that would replace a human employee in the service industry.


I thought this was going to be about AI replacing workers in the service industry.


What borders me, is that you need an valid SSL cert for an service worker, however there is a develop/test cert here: https://github.com/Eun/test.bi


I don't get it, how is one supposed to use that, if the domains point to your IP addresses?


It's evidently for local work, /etc/hosts file is included in the repo.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: