Last active
February 14, 2018 00:20
Star
You must be signed in to star a gist
PromiseWorker ServiceWorker example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<title> | |
PromiseWorker ServiceWorker example | |
</title> | |
<body> | |
<h1>PromiseWorker ServiceWorker example</h1> | |
<pre id="display"></pre> | |
<script src="https://npmcdn.com/promise-worker/dist/promise-worker.js"></script> | |
<script src="main.js"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function log(str) { | |
console.log(str); | |
display.innerHTML += str + '\n'; | |
} | |
if (!('serviceWorker' in navigator)) { | |
log('serviceWorker unavailable in this browser, canceling'); | |
} else { | |
navigator.serviceWorker.register('worker.js', { | |
scope: './' | |
}).then(function (registration) { | |
if (navigator.serviceWorker.controller) { // already active and controlling this page | |
return navigator.serviceWorker; | |
} | |
return new Promise(function (resolve, reject) { | |
registration.addEventListener('updatefound', function () { | |
var newWorker = registration.installing; | |
newWorker.addEventListener('statechange', function () { | |
if (newWorker.state == 'activated' && navigator.serviceWorker.controller) { | |
resolve(navigator.serviceWorker); | |
} | |
}); | |
}); | |
}); | |
}).then(function (worker) { // the worker is ready | |
var promiseWorker = new PromiseWorker(worker); | |
var msg = {hello: 'worker'}; | |
log('Sending message to worker: ' + JSON.stringify(msg)); | |
return promiseWorker.postMessage(msg); | |
}).then(function (response) { | |
log('Got response: ' + JSON.stringify(response)); | |
}).catch(log); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
importScripts('https://npmcdn.com/promise-worker@1.1.1/dist/promise-worker.register.js'); | |
registerPromiseWorker(function (msg) { | |
return {hello: 'main thread'}; | |
}); | |
self.addEventListener('activate', function(event) { | |
event.waitUntil(self.clients.claim()); // activate right now | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment