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

384
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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