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?
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();
});