Skip to content

Instantly share code, notes, and snippets.

@greenido
Last active September 27, 2015 21:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save greenido/1338056 to your computer and use it in GitHub Desktop.
Save greenido/1338056 to your computer and use it in GitHub Desktop.
Shared Web Workers: Show And Tale
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<title>Shared Web Workers: Show And Tale</title>
</head>
<body>
<h1>Shared Web Workers: Show And Tale</h1>
<article>
To create a shared web worker, you pass a JavaScript file name to a
new instance of the SharedWorker object:
<br/>var worker = new SharedWorker("jsworker.js");
<br/>
<output id="result"></output>
</article>
<script>
var worker = new SharedWorker('sharedWorker.js');
worker.port.addEventListener("message", function(e) {
document.getElementById('result').textContent += " | " + e.data;
}, false);
worker.port.start();
// post a message to the shared web worker
console.log("Calling the worker from script 1");
worker.port.postMessage("script-1");
</script>
<script>
console.log("Calling the worker from script 2");
worker.port.postMessage("script-2");
</script>
</body>
</html>
//
// sharedWorker.js
// Shared workers that handle the connections and Welcome each new script
//
var connections = 0; // count active connections
self.addEventListener("connect", function (e) {
var port = e.ports[0];
connections++;
port.addEventListener("message", function (e) {
port.postMessage("Welcome to " + e.data +
" (On port #" + connections + ")");
}, false);
port.start();
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment