Uau, I didn't know about that but all indicates that it is possible to load web worker directly as a module.
Before, I was loading the script via HTTP passing the public path, note that I am using a React application with Vite.
Old example:
I didn't like this way of loading web workers because I was forced to write it as a javascript file, and I couldn't import other modules inside that. Take a look:
Web Worker script: public/get-merchant-ids-from-csv.js
self.onmessage = function handleMessageFromMain(message) {
/**
* @type {File}
*/
const file = message.data;
const result = new FileReader();
result.readAsText(file);
result.onloadend = function () {
const merchantIds = extractValues(result.result);
self.postMessage(merchantIds);
};
};
function extractValues(result) {
const [, ...rows] = result.split('\n');
const values = rows.map((row) => {
const items = row.split(',');
return items.reduce((_, item, index) => {
return String(item).trim();
}, []);
});
return values;
}
Invoking the web worker from the public directory
// NOTE: In my case I needed to specify the base URL, but in most of cases you can write the URL starting with "/"
const GET_MERCHANT_IDS_FROM_FILE_WORKER = `${BASE_URL}/get-merchant-ids-from-csv.js`;
const worker = new Worker(GET_MERCHANT_IDS_FROM_FILE_WORKER);
Prefered way example:
Web worker script: src/modules/shared/workers/get-merchant-ids-from-csv.ts
Note that it is a typescript now
self.onmessage = function handleMessageFromMain(message: MessageEvent<File>) {
const file = message.data;
const result = new FileReader();
result.readAsText(file);
result.onloadend = function () {
const merchantIds = extractValues(String(result.result));
self.postMessage(merchantIds);
};
};
function extractValues(result: string) {
const [, ...rows] = result.split('\n').map((row) => row.trim());
return rows;
}
The new way of importing the web worker:
const worker = new Worker(
new URL(
'../../shared/workers/get-merchant-ids-from-csv.ts',
import.meta.url,
),
{
type: 'module',
},
);
Now, it is possible to import other modules, and independent of the place where the script is located, we can inform the path and import it. Note that it is important to pass as a second parameter the base URL import.meta.url
(exposed by vite build system)
Top comments (0)