A Pen by Ronnie Overby on CodePen.
Created
July 1, 2015 16:07
-
-
Save ronnieoverby/8f2f81163d14ff85fdf5 to your computer and use it in GitHub Desktop.
YXepZj
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
<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> |
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
$(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?'); | |
}); | |
}); |
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
<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