Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

321
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda