Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

319
Views
JavaScript Web Workers - Cross-browser importScripts with module

I have a JavaScript module like so:

function difference(a, b){
        
    return a - b;

}

export {difference};

This works fine when importing it into my main script.

import * as MathUtils from './math-utils.js';

However, I want to also import it into a Web Worker. The only cross-browser way to do this seems to be the following:

self.importScripts('/scripts/math-utils.js');

I obviously get an error when doing this because of the export statement at the end of the module. Is there any way to import the same script into a Web Worker that is cross-browser? Or at least to pass the functions to the Web Worker from the main script?

Thanks in advance!

Update:

I came up with this polyfill, which needs to be called from within the onmessage function of the Worker. However, this is not a very elegant solution and I would appreciate it, if anyone knew of a better way.

function importScript(path){
    
    return new Promise((resolve, reject) => {

        fetch(path).then((response) => {

            if(response.status == 200){

                return response.text();

            }
        
        }).then((script) => {
        
            if(typeof(script) == 'undefined'){

                // Import failed

                reject();

            }
            else{

                // Remove export statement from script

                script = script.replace(/export(.*);/m, '');

                // Create blob

                var blob = new Blob([script], {type : 'text/javascript'});
                var url = URL.createObjectURL(blob);
            
                self.importScripts(url);

                resolve();

            }

        });

    });

}

Edit: This is not a duplicate of Web Workers - How To Import Modules!

The accepted answers on that question only accounts for Chromium-based browsers, I am looking for a cross-browser solution.

about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!