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

259
Vistas
Is it safe to call a function from imported module inside document ready event?

I want to call a function from imported module when DOM is rendered. What makes me doubt the safety of this is the fact that module files are fetched asynchronously. My worry therefore is: Is it possible that required module file is fetched after the document is ready?

import someModule from '../someModule.js'

$( document ).ready(function() {
    someModule.hello();
});

Is this code safe?

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

That code is safe.

If you were using DOMContentLoaded and not $(document).ready, it may well be something to worry about. Modules are loaded asynchronously, and everything that a module itself imports is loaded before the body of the module runs. That is:

import someModule from '../someModule.js'

will first be resolved to a value of the someModule export, and only then will the rest of the module run:

$( document ).ready(function() {
    someModule.hello();
});

The rest of the document may have finished loading in that time, especially if there are more import chains higher up in the dependency tree, and the source HTML is short.

But $(document).ready will not only run its callback when the document is ready, it'll also run its callback if the document is already ready - which can be checked with document.readyState.

Example:

setTimeout(() => {
  // the document will have been fully loaded for ages now,
  // but the callback will still run:
  $(() => {
    console.log('running');
  });
}, 5000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If you were using DOMContentLoaded instead, to be safe, you'd need to use

if (document.readyState === 'complete') {
  someModule.hello();
} else {
  window.addEventListener('DOMContentLoaded', () => someModule.hello());
}

Also note that in jQuery, the preferred modern way of scheduling a callback when the document is ready is to just pass the callback to $:

$(() => {
    someModule.hello();
});
about 4 years ago · Santiago Gelvez 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