workers of the web

The n00b intro

what is a worker?

Generally speaking, a worker is a thread that runs in parallel with your application, outside of its normal lifecycle.

 

It is usually used to run expensive tasks that would otherwise slowdown the main application, since it makes use of our multiple CPUs.

but... web apps are single-threaded

Normally, a web application is only able to execute one thread at any time.

 

This can sometimes impact the response time (and ultimately, the FPS) of the app.

(Web) workers à la rescousse!

Adding one or multiple workers to a web app will allow you to run multiple threads.

 

And so much more!

web/shared/service workers... wat?

There is a lot of confusion and fluctuation around workers of the Web.

 

Here is my succinct analysis...

 

(For more, check this awesome article.)

web worker: the muscle

It is mostly used to crunch big calculations and avoid blocking the UI.

 

Supported by ~90% of browsers.

 

Example: http://afshinm.github.io/50k/.

Links: this, this and this.

shared worker: the mia

You will see it mentioned, but it was dropped from webkit and slowly abandoned.

 

Supported by ~47% of browsers.

 

Don't use it.

service worker: the trickster

It essentially acts as proxy that sits between the app, the browser and network (when available). It has/will have access to cache, push notifications and background sync APIs. It is used mostly in the context of offline apps.

 

Supported by ~59% of browsers.

 

Examples: this, this and that.

Links: this and that.

to summarize...

The web worker will help you keep your app running smooth when executing expensive operations.

 

The service worker will let you gracefully take your app offline and behave more like a native one.

the gotchas (all)

No worker can interact with the DOM or have access to document, window, console, parent.

 

Communication must go through the worker’s postMessage method.

 

The worker logic and code must live in an separate external file.

 

 

the gotchas (web)

It is quite heavy to run.

 

It needs to be terminated (or it will just stay active).

 

It does not provide a Promise API out of the box.

the gotchas (service)

You can't rely on its state, as it is punctually turned on and off by the browser.

 

It require HTTPS (thank God).

Any questions?

Thanks for listening!

 

Twitter: @sim_walsh

GH: @simonwalsh

Workers of the Web: The n00b intro

By Simon Walsh

Workers of the Web: The n00b intro

High-level presentation on web and service workers: what they are, what they aim at doing, how to use them and they specificities.

  • 980