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

385
Visualizações
How to import javascript function from file without running entire js file?

I have page1.html which uses blah.js. One of the things blah.js does is run a function1() when the page is loaded. I would like to use function2() from blah.js in page2.html without blah.js running function1(). I thought I could add

export {function2}

to blah.js and then just import function2() by adding

<script type = "module">
import { function2 } from './blah.js'
</script>

to page2.html. But this seems to have the same functionality as if I just imported the file as normal:

  <script defer src="blah.js"></script>

i.e. function1() runs in page2 in both cases. How can I get access to function2() without running the other parts of blah.js?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you import from a module, all of that module's top-level code will run. That is, given

console.log('running');
export const foo = 5;

There is no way to import foo without also logging the text.

One good approach to this problem (and a very good practice in general) is to avoid side-effects at the top level of modules. If you have something that's a side-effect, put it into a function instead, and export that function, so that it only runs on demand, instead of every time anything from the file is imported.

So, you probably want to change your file to something like:

export const runFunction1WhenPageLoads = () => {
  const fnToRun = () => {
    // insert code here
  };
  if (document.readyState === 'complete') {
    fnToRun();
  } else {
    window.addEventListener('DOMContentLoaded', fnToRun);
  }
};
export const function2 = () => {
  // insert code here
};
about 4 years ago · Juan Pablo Isaza Relatório
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