Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!