Home > Net >  HTML - Adding the script in the head or in the body (to translate the DOM)?
HTML - Adding the script in the head or in the body (to translate the DOM)?

Time:08-29

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?

CodePudding user response:

See the MDN documentation for script elements:

defer

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating.

Warning: This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect.

The defer attribute has no effect on module scripts — they defer by default.

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.

CodePudding user response:

you can use defer in script attribute. or write the script tag under the body tag, In the html tag.

  • Related