Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

323
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda