Skip to content

Instantly share code, notes, and snippets.

@singh-shweta
Last active May 10, 2020 17:21
Show Gist options
  • Save singh-shweta/444368ee98b217314852cc5c7e78d3eb to your computer and use it in GitHub Desktop.
Save singh-shweta/444368ee98b217314852cc5c7e78d3eb to your computer and use it in GitHub Desktop.
Worker examples
import workerFile from "./worker";
export let logWorker, sendLog;
/**Checking if browser supports Workers */
if (window.Worker) {
logWorker = new Worker(workerFile); //initiates a worker thread
sendLog = (msg) => {
logWorker.postMessage(msg); //postMessage helps to communicate with the worker thread.
}
logWorker.onmessage = function(e) {
/** message event is triggered by the worker when some message is sent from worker thread */
console.log('Message from Worker: ' + e.data);
};
} else {
console.log('Your browser doesn\'t support web workers.')
}
const workercode = () => {
// eslint-disable-next-line no-restricted-globals
self.onmessage = function (e) {
console.log("Worker: Message received from main script", e.data);
/** Here data passed is an object and i am accessing the type property passed from the main thread */
if (e.data.type) {
console.log(e.data);
}
let { type, href, fromProduct, user } = e.data;
if (type === "navigation") {
console.log(`User ${user} navigated from ${fromProduct} to ${href}`);
postMessage("Log printed!"); //postMessage helps to communicate with the main thread.
}
};
};
/** Below lines are added as it gives me a url for the file contents which i can use to initialize my Worker thread using import. */
let code = workercode.toString();
code = code.substring(code.indexOf("{") + 1, code.lastIndexOf("}"));
/**The URL.createObjectURL() static method creates a DOMString containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object. */
const blob = new Blob([code], { type: "application/javascript" });
const worker_script = URL.createObjectURL(blob);
module.exports = worker_script;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment