Skip to content

Instantly share code, notes, and snippets.

@zdychacek
Last active February 15, 2017 20:12
Show Gist options
  • Save zdychacek/827bc4ab6e96d0108cc6c1f6bf48dd20 to your computer and use it in GitHub Desktop.
Save zdychacek/827bc4ab6e96d0108cc6c1f6bf48dd20 to your computer and use it in GitHub Desktop.
Inline Web Worker
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Inline Web Worker</title>
</head>
<body>
</body>
<script type="javascript/worker" id="my-worker">
self.addEventListener('message', function (event) {
// echo received data back to main thread
postMessage(event.data);
}, false);
</script>
<script>
// load worker
loadInlineWorker('#my-worker', function (worker) {
worker.addEventListener('message', function (event) {
// send data to worker thread
worker.postMessage({});
}, false);
});
// helper for loading inlined web worker
function loadInlineWorker (selector, callback) {
window.URL = window.URL || window.webkitURL;
var script = document.querySelector(selector);
if (script.type === 'javascript/worker') {
var blob = new Blob([ script.textContent ]);
callback(new Worker(window.URL.createObjectURL(blob));
}
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment