iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🙆
How to use cross-origin Web Workers
I have migrated this article following a change in my Google account.
Goals and Prerequisites
- There is a process to be executed in a Worker thread.
- Web Worker JS files cannot be placed within the same repository.
- Wanting to host it on S3 or GitHub Pages to use across multiple contents.
Preparing the Script for the Web Worker
Implement some process for the Worker thread.
In this example, it simply multiplies two passed values and returns the result.
Once the implementation is complete, deploy it to a service capable of static hosting. In this case, I uploaded it to GitHub Pages.
https://mktbsh.github.io/assets/js/workers/sample.worker.js
sample.worker.js
onmessage = (e) => {
console.log('Message received from main thread');
var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
console.log('Posting message back to main thread');
postMessage(workerResult);
}
Implementing the Main Thread Process
sample.js
(function () {
// URL of the script that implements the Web Worker process
const crossOriginScriptUrl = 'https://mktbsh.github.io/assets/js/workers/sample.worker.js';
// Create Worker object
const workerUrl = getWorkerURL(crossOriginScriptUrl);
const myWorker = new Worker(workerUrl);
// Revoke the object URL
URL.revokeObjectURL(workerUrl);
// Receive the result from the Worker thread
myWorker.onmessage = (e) => console.log(e.data);
document.getElementById('button').addEventListener('click', () => {
const value1 = 100;
const value2 = 1000;
myWorker.postMessage([value1, value2]);
});
function getWorkerURL(url) {
const content = `importScripts("${url}");`;
return URL.createObjectURL(new Blob([content], {
type: 'text/javascript'
}));
}
})();
Reference Links
Discussion