Should javascript code always be loaded at the head of an html document?

Is there a general rule in terms of javascript loading? I see that people are saying that now it should go at the end of the page.

Thoughts?

+3
source share
5 answers

Well, there are two cases (at least) depending on what you want to achieve. If you need functionality built into a script or scripts, such as function libraries, available before or during page loading, you must load the JavaScript code in the header tag. If you need to do something that requires some resources that will be available only after loading the page (the DOM resources that are), you should load script / s at the bottom of the page (this can also be solved using onDOMReady events that are already available in most JavaScript frameworks). There may be some performance issues that may dictate your decision. For example, there are situations when loading a script or scripts in the head tag slows down the rendering of pages, and if you can provide basic functions using a page,displayed until the script is fully operational, then again the script or scripts should be loaded from below. This is more or less a decision based on what you need to do.

+3

, , - , . JavaScript , , , .

jQuery ready:

, DOM .

, , , , -.

, JavaScript - , JavaScript HTTP- ( , CSS ..) , .

+8

: , Js , . , , , .

-, JS, , , . -, , Yahoo! , script.

N.B: script DOM. , onload $.ready. , , .

+2

javascript , - , . javascript - , , <script> </body>.

: http://developer.yahoo.com/performance/rules.html

+2

I like to collapse my code into a single file when deployed to production. Thus, during development, I create one file for each JavaScript class and load each into the head ( after the CSS files). Since I am waiting for an event from the browser to indicate that the DOM is ready, I put my JS file at the top of only the HTML / JSP page.

+1
source

Source: https://habr.com/ru/post/1723408/


All Articles