0

Javascript, do 'placing' matters on the source code?

I am currently studying the basic concepts of javascript here in sololearn and I am confused about the <script> tag written on html. They say I can put it on head, body and on the bottom. I can't seem to move on without this confusion gets cleared 😲

25th Apr 2018, 6:16 AM
Joshuel Ernest Q. Simbulan
Joshuel Ernest Q. Simbulan - avatar
4 Respostas
+ 2
Hi JaZe Web code is executed from top to bottom. JavaScript is by default single threaded, which means that it will block the browser if it has to do work. So it is common practice to place the scripts at the end of the Body of HTML so that the HTML has rendered before JavaScript executes. This means that your users get to see a page before any blocking of code might occur. However we now have new tags in HTML 5 that help with this blocking behaviour. You can specify <script async>, and <script defer> async downloads the file during HTML parsing and will pause the HTML parser to execute it when it has finished downloading. defer downloads the file during HTML parsing and will only execute it after the parser has completed. defer scripts are also guaranteed to execute in the order that they appear in the document. Modern Browsers also support Web Workers that can do some of your work in the background.
25th Apr 2018, 7:17 AM
Mike Choy
Mike Choy - avatar
0
Placing script tags in head: This is done when ypu want to include external libraries or frameworks Placing scripts in body: When a script is placed in the body it should be at the bottom so all the markup would have fully loaded before the script us run
25th Apr 2018, 6:28 AM
᠌᠌Code X
᠌᠌Code X - avatar
0
ngbrains, do you mean the time of execution changes depending on where I put the tag?
25th Apr 2018, 6:30 AM
Joshuel Ernest Q. Simbulan
Joshuel Ernest Q. Simbulan - avatar
0
or not, I am still confused
25th Apr 2018, 6:30 AM
Joshuel Ernest Q. Simbulan
Joshuel Ernest Q. Simbulan - avatar