Answer the question
In order to leave comments, you need to log in
Where is the best place to include js?
Where and in what way is it most efficient to connect scripts to a page?
Previously connected to head
(with $.ready
either DOMContentLoaded
). Now everything points to it at the end body
. Of course, the second option is much more efficient. With this connection, the situation is as follows: the page is loaded first, then the scripts.
As for me, the most effective option is to include scripts in head
, but with defer
(which loads scripts asynchronously, scripts are executed after DOM construction, in strict sequence (unlike async
), and is defer
supported everywhere):
At the same time, scripts start loading in<script defer src="js/main.js"></script>
head
, the page continues to load, and as a result, the scripts will load as many milliseconds faster as the browser takes to build the page (from 100 milliseconds to several seconds).
PS It's just that they will connect everything at the end body
, and gradually I begin to doubt my reasoning
Answer the question
In order to leave comments, you need to log in
they are connected mainly at the end of the body, because it is important to keep the sequence of loading and executing scripts, for example jquery, and then some common.js that uses jquery.
+ in this case, the loading of scripts will start at the very end, when html is parsed.
Those. let's say you have a script in the head that weighs ~ 10mb, but it defer and did not criticize (you can then load it lazily later), in this case it will start loading immediately, and the html parsing will continue further, then you have other pictures in html , media files, etc. - but if you have a weak connection, then the entire channel will be eaten by this script.
but in general, if you have an attribute - defer or async, then in principle it does not matter where you connect your script.
here is a diagram of different options for connecting the script:
https://hospodarets.com/img/blog/14828583238612140...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question