+ 1

Jquery/javascript best practice best practice

Should javascrpit/jquery code be put in the head section of the html document or just before the closing body tag?? Which of these is considered best practice?? Cheers!!

14th Jul 2017, 3:34 AM
Kayode Oluwafemi
Kayode Oluwafemi - avatar
1 Resposta
+ 1
It depends on what you're doing with the code. Usually it's best to place your JS in a separate file and link to it with a script tag. Usually you'd place your script tag at the bottom of the body if the code in the JS is dependent on whether or not the DOM has been created. Since the html file is read top down by the browser this will ensure that the pages elements exist when the JS code runs. Likewise, you could use the onload function or the JQuery document.ready() function ($) to ensure that the DOM has been created. That being said there may be times that you want your JS code to run prior to the page loading or the DOM being created. In those cases place your script tags in the head.
14th Jul 2017, 4:12 AM
ChaoticDawg
ChaoticDawg - avatar