Last active
February 15, 2017 20:12
-
-
Save zdychacek/827bc4ab6e96d0108cc6c1f6bf48dd20 to your computer and use it in GitHub Desktop.
Inline Web Worker
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> | |
<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