Skip to content

Instantly share code, notes, and snippets.

@ronnieoverby
Created July 1, 2015 16:07
Show Gist options
  • Save ronnieoverby/8f2f81163d14ff85fdf5 to your computer and use it in GitHub Desktop.
Save ronnieoverby/8f2f81163d14ff85fdf5 to your computer and use it in GitHub Desktop.
YXepZj
<script type="text/js-worker" id="answerUltimateQuestion">
onmessage = function (msg) {
// TODO: long running code that uses msg.data to figure out answer to everything
postMessage(42);
};
</script>
<button id="ask">What is the answer?</button>
$(function() {
// normally you create a worker with new Worker('myworker.js');
// but I can't do that here because worker requires same origin
// so instead I'm using an "embedded worker" for this demo:
// thanks mozilla for the idea of an embedded worker script:
// https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Embedded_workers
var workerScript = $('#answerUltimateQuestion').get(0);
var blob = new Blob([workerScript.textContent], {
type: "text/javascript"
});
var worker = new Worker(window.URL.createObjectURL(blob));
// okay the worker is created
// let's define what happens when worker posts a message to us:
worker.onmessage = function(msg) {
alert(msg.data);
}
// and let's setup a way to send messages to the worker:
$('#ask').click(function() {
worker.postMessage('do i exist?');
});
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment