JSFiddle - React, Tailwind, and code Playground
by ChaseMoskal
HTML
<div id="counter"></div>
<script id="myWorker">
document.write("<em>Awkward!</em> This code is running in the main thread -- not as a web worker! We are only able to document.write this message just now, because we are in the main thread who has DOM access. <br /><br /> Because of the article's fatal flaw, the code in this script tag will run once for the main thread, and then the JavaScript for this page (fiddle pane below) loads the script into a web worker to run it again! This means this code would be running both in the main thread (failing on postMessage), and *also* as a web worker! ACHK! That's seriously catastrophic. Luckily for right now, this web-worker thread will hit this document.write call, and immediately fail and terminate. Check the console, and see 'document is not defined'? This attempt to access the DOM is killing the web worker thread, which also kills the counter demo. As a side-note, web worker access is *so* restricted, that we don't even have access to the console object, so we can't even console.log from a web worker.");
var i = 0;
setInterval(function() {
i++;
postMessage(i);
}, 500);
</script>
JavaScript
var myWorker = null,
URL = window.URL || (window.webkitURL);
window.URL = URL;
var workerData = new Blob([document.getElementById('myWorker').textContent], {
type: "text/javascript"
});
function init() {
if (typeof (Worker) === undefined) {
alert('No webworker supported');
return false;
}
myWorker = new Worker(window.URL.createObjectURL(workerData));
myWorker.onmessage = function (e) {
document.getElementById('counter').innerHTML = e.data;
};
}
init();