+ 1
Script tag should be in which part? Body or head?
6 Antworten
+ 8
It can be both. Placing script in body tag is better in some cases as it helps webpages to load faster
+ 7
I second with Muhd Khairul Amirin Bin Yaacob due to the fact that resources are loaded from top to bottom in HTML document and browsers limit the concurrent HTTP connection at one time.
Therefore huge resources on the top may delay following resources going to load.
Therefore the general concensus is:
✅ Place on the top if it affects the presentation/display to prevent FOUC (a.k.a. Flash of Unstyled Content)
✅ Otherwise place it at the bottom if it won't affect the interactivity of the site once the page load up but not fully loaded.
💡 INFO
https://en.m.wikipedia.org/wiki/Flash_of_unstyled_content
+ 1
Actually the answer is both.
You can add your script in head as well as in body tag but recommended way is to add just above closing tag of body.
+ 1
I would suggest always putting it before closing body tag. I never heard that it helps to load pages faster though. The main purpose of this is to load DOM before JS is loaded. So you are not getting errors like null and undefined when working with DOM.
+ 1
Just to add a little more to the good answers already posted, choosing the best spot for your scripts depends on what's in them and how they interact with the document (like damyco was saying, if the document needs to be there before the scripts manipulate its content, then it should be placed at the end of the body). There may be some browser compatibility issues with async, but not everyone needs to worry about that. I tend to put analytics and tracking-related scripts in the head because I think of it as metadata (conceptual grouping) and so they trigger even if the user stops the page from fully loading (hooray for skewed statistics!) but others may find that undesirable. Also, you'll want to ensure that those scripts are accounting for the async issue because if they don't, it could backfire. I was investigating a potential client once and when I went to visit their existing website to get a feel for potential issues to fix, one of their tracking scripts overwhelmed my browser and froze my computer.
0
Ok.. Thank you all of you