Why is it recommended to place Javascript codes at the end of the body tag scope?

Asked

Viewed 1,015 times

5

Do you have any rules regarding the use of scripts in tag <head>? W3C did not make the rules of use very clear.

1 answer

4


Because then the main elements of the page and that should be the most relevant can already be rendered before the end of the verification and interpretation of the parts in JS that are usually important only after the end of the page load.

If the JS code is placed at the beginning or middle, the page rendering is blocked until the whole script be analyzed.

Obviously this does not work so well in all cases. It may be that the correct and complete rendering is only possible when the script starts running.

There are a number of techniques to better control this load and in few cases this recommendation should be followed.

So nothing prevents and in general put in the tag head is advantageous, especially if charging asynchronously or with delay:

<script defer>

or

<script async>

Behold how it works.

Where can you use the defer.

Where can you use the async.

  • thanks for the explanation!

  • @Ivanferrer I posted there in duplicate, and added some extra details.

  • I believe that your answer made things clearer, I had already researched the question they considered duplicated, but it did not completely clear my doubt. Now that you’ve published your answer in duplicate, I believe it will help more people.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.