+ 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)

8th Apr 2018, 6:21 AM
Robin Singh
Robin Singh - avatar
3 odpowiedzi
+ 4
the script tag should be the last tag in the body to prevent premature running of the script
8th Apr 2018, 6:31 AM
᠌᠌Code X
᠌᠌Code X - avatar
+ 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.
8th Apr 2018, 6:39 AM
Robert 🇳🇬
Robert 🇳🇬 - avatar
+ 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
8th Apr 2018, 8:02 AM
KrOW
KrOW - avatar