I am doing the following to translate my html page:
<head>
<script type="module" src="js/scripts/home.js"></script>
</head>
<body>
<h1 id="hello">Hello world!</h1>
</body>
and
import $ from "jquery";
import { t } from "../lib/i18n";
function main() {
$("#hello").text(t("hello"));
}
main();
I do not understand why this work, I thought that, in order to manipulate the DOM, we should wait to get it ready…
By the other hand, if I add the script at the end of the body tag, the look-and-feel is worse, because there is a little timeout before the translation.
<body>
<h1 id="hello">Hello world!</h1>
<script type="module" src="js/scripts/home.js"></script>
</body>
Another option, with the same behavior, is to include the script at the head but change the js code to:
import $ from "jquery";
import { t } from "../lib/i18n";
function main() {
$("#hello").text(t("hello"));
}
$(main); // on DOM ready <---------
What is the suggested way to go here and why?
2
Answers
See the MDN documentation for script elements:
Since it is a module, it is automatically deferred, so won’t run until the DOM is ready, thus you don’t need to write any JS to explicitly wait for the DOM to be ready.
you can use defer in script attribute.
or write the script tag under the body tag, In the html tag.