Skip to content

Instantly share code, notes, and snippets.

@zazaulola
Created July 20, 2024 05:31
Show Gist options
  • Save zazaulola/f7990ac56801d08e89e1bfc177c1333b to your computer and use it in GitHub Desktop.
Save zazaulola/f7990ac56801d08e89e1bfc177c1333b to your computer and use it in GitHub Desktop.
Create local worker without HTTP request
export function createWorker(callable) {
const code = `(${callable.toString()})()`;
const blob = new Blob([code], { type: 'text/javascript' });
const url = URL.createObjectURL(blob);
const worker = new Worker(url);
URL.revokeObjectURL(url);
return worker;
}
export function executeWorker(callable, data) {
return new Promise((res) => {
const worker = createWorker(callable);
worker.postMessage(data);
worker.onmessage = ({ data }) => {
worker.terminate();
res(data);
};
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment