Skip to content

Instantly share code, notes, and snippets.

@numberoverzero
Last active August 29, 2015 14:00
Show Gist options
  • Select an option

  • Save numberoverzero/11386797 to your computer and use it in GitHub Desktop.

Select an option

Save numberoverzero/11386797 to your computer and use it in GitHub Desktop.
Basic web worker
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
</head>
<body>
<div>Type some stuff and click send (or hit enter)</div>
<input type='text' id='input' onkeyup="onKeyUp(event)" autofocus="autofocus"></input>
<button onclick='send_text()'>Send</button>
<div id='output'></div>
<script id='worker' type='javascript/worker'>
// Runs on worker
function send(object) {
self.postMessage(object);
}
function receive(obj) {
var response = {
methodName: 'echo',
arg: obj
};
send(response);
}
self.onmessage = function(e) { receive(e.data); };
</script>
<script id='main'>
// Worker stuff
var blob = new Blob([document.querySelector('#worker').textContent]);
var worker = new Worker(window.URL.createObjectURL(blob));
function send(obj) {
worker.postMessage(obj);
}
function receive(obj) {
log('worker->main$ ' + JSON.stringify(obj));
log('-------------------------');
}
worker.onmessage = function(e) { receive(e.data); };
// Hook up html input/output to worker
var input = document.getElementById('input');
function send_text() {
var text = input.value.trim();
input.value = '';
input.focus();
if(text) {
send(text);
log("main->worker$ " + text);
}
}
var output = document.getElementById('output');
function log(text) {
output.innerHTML = output.innerHTML + '<div><code>' + text + '</code></div>';
}
function onKeyUp(e) {
var charCode = (typeof e.which === "number") ? e.which : e.keyCode;
if(charCode === 13) {
send_text();
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment