Created
April 12, 2018 14:03
-
-
Save inkdeep/aaab3f60bc3b4a4ab32e81125ab19b29 to your computer and use it in GitHub Desktop.
Experimenting with ways to take JavaScript on the client and make web workers with it.
This file contains hidden or 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 workerMessageHandler({ data, origin, lastEventId, source, ports }) { | |
console.warn(`worker got message | |
data: ${JSON.stringify(data)} | |
origin: ${origin} | |
lastEventId: ${lastEventId} | |
source: ${source} | |
ports: ${ports} | |
`); | |
self.addEventListener("message", function(e) { | |
postMessage(x * 2); // Intentional error. 'x' is not defined. | |
}); | |
postMessage(`got your message: ${JSON.stringify(data)}`); | |
} | |
function aWorker(handler) { | |
return `onmessage = ${handler}`; | |
} | |
function workerFactory() { | |
const workerBlob = new Blob([aWorker(workerMessageHandler)], { | |
type: "text/javascript" | |
}); | |
const workerDataUrl = URL.createObjectURL(workerBlob); | |
const myWorker = new Worker(workerDataUrl); | |
myWorker.onmessage = function({ data, origin, lastEventId, source, ports }) { | |
console.log(`message from worker: | |
data: ${data} | |
origin: ${origin} | |
lastEventId: ${lastEventId} | |
source: ${source} | |
ports: ${ports} | |
`); | |
}; | |
myWorker.onerror = function({ lineno, filename, message }) { | |
console.error(`ERROR in worker: | |
Line: ${lineno} | |
In: ${filename} | |
Message: ${message} | |
`); | |
}; | |
myWorker.postMessage({ type: "example", data: [1, 2, 3, 4] }); | |
return myWorker; | |
} | |
const PeepIt = workerFactory(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment