Forem

Pedro Oliveira
Pedro Oliveira

Posted on

Invoking Web Worker as a module

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;
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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',
  },
);
Enter fullscreen mode Exit fullscreen mode

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)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

đź‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay