+ 3
Which method is better to put the JS code?
1.in head tag. 2.in body tag. Is there any difference between theses two methods. (when we don't want to link any external JS file)
3 ответов
+ 4
the script tag should be the last tag in the body to prevent premature running of the script
+ 1
The script tag should come last in the body. This is to allow the HTML elements to load first before the script is run.
+ 1
Depends.... If it is utility script (support other scripts) insert in head but if it must run "soon" insert in body... Most time it inserted at end but for me is not really necessary, more important is that, if it access DOM, it get called after DOM is inited (with window.onload or window.addEventListener). If your script must insert some other content if user not has js support then put it in body and use noscript tag