Created
August 20, 2018 09:59
-
-
Save Ashkanph/a9c18e8eee6eae14832cf1695f22e77a to your computer and use it in GitHub Desktop.
Using web workers in react js
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
/* ------- worker file ---------- | |
./worker/myworkercode.js | |
*/ | |
const workercode = () => { | |
self.onmessage = function(e) { | |
// Do anything you want with e.data | |
let l = e.data * 5; | |
postMessage(l); // return new data | |
} | |
}; | |
let code = workercode.toString(); | |
code = code.substring(code.indexOf("{")+1, code.lastIndexOf("}")); | |
const blob = new Blob([code], {type: "application/javascript"}); | |
const worker_script = URL.createObjectURL(blob); | |
module.exports = worker_script; | |
/* ------- react component ---------- | |
*/ | |
import worker_script from './worker/myworkercode.js'; | |
let myWorker = new Worker(worker_script); | |
// In component class codes | |
if (window.Worker) { // Check if Browser supports the Worker api. | |
let dataForWorker = 50; | |
myWorker.postMessage(dataForWorker); | |
myWorker.onmessage = (e) => { | |
console.log("data received from worker: ", e.data); | |
}; | |
}else{ | |
console.error('Your browser does not support worker'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment