// Everything between here...
$.getJSON('/payload.json', function (response) {
// ... and here is free, right?
});
response.json())
// index.js
var worker = new Worker('worker.js');
worker.postMessage('ping');
worker.onmessage = function (e) {
console.log(e.data); // 'pong'
};
// worker.js
self.onmessage = function (e) {
console.log(e.data); // 'ping'
self.postMessage('pong');
};
// index.js
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register(
'/service-worker.js');
}
// service-worker.js
self.addEventListener('fetch',
function (e) {
e.respondWith(fetch(e.request));
}
);
Web Workers | Service Workers | |
---|---|---|
Tab control | Many per tab | One for all tabs |
Lifespan | Same as tab | Independent |
Good for | Parallelism | Offline |
fetch()
console
in Android <5// index.js
var pw = new PromiseWorker(
new Worker('worker.js'));
pw.postMessage('yo').then(supports => {
if (!supports) {
// fall back to worker polyfill
}
});
// worker.js
registerPromiseWorker(msg => {
return !!self.indexedDB;
});
// index.js
var worker = new PseudoWorker(
'worker.js');
var pm = new PromiseWorker(worker);
pm.postMessage('yo').then(msg => {
// ...
});
// worker.js
registerPromiseWorker(msg => {
// This will run on the main thread!
});