/    Sign up×
Community /Pin to ProfileBookmark

Placement of Script element within HTML

This…

“`html
<html>
<body>
<h1>Hello world!</h1>
</body>
<script src=”script.js”></script>
</html>
“`

And this…

“`html
<html>
<body>
<h1>Hello world!</h1>
<script src=”script.js”></script>
</body>
</html>
“`

I have seen both examples. What’s the difference, or which one is more “correct”? It has something to do with order in which page is rendered and script is loaded? Shouldn’t `<script>` elements be placed within `<head>` element?

This is what I expect to see…

“`html
<html>
<head>
<script src=”script.js”></script>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
“`

to post a comment
HTML

3 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumSep 19.2020 — >Shouldn't <script> elements be placed within <head> element?

Not necessarily. Often scripts refer to DOM elements and it must be made shure that these elements exist when they are referenced. This is the case when the script is placed at the end of the body. If placed in the head you will have to use the event "DOMContentLoaded" as explained here:

https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event

In some special cases, e. g. when the script reads the dimensions of an image, the load event has to be used instead.
Copy linkTweet thisAlerts:
@DescartesauthorSep 19.2020 — @Sempervivum#1623435 the example above is something I saw in a discussion about DOM manipulation. So placing &lt;script src="script.js"&gt;&lt;/script&gt; within &lt;html&gt;&lt;/html&gt; and outside of &lt;body&gt;&lt;/body&gt; and &lt;head&gt;&lt;/head&gt; is ideal when working with a single index.html and using DOM to change the view?
Copy linkTweet thisAlerts:
@SempervivumSep 19.2020 — Above or below `&lt;/body&gt;` - this is discussed here:

https://stackoverflow.com/questions/3037725/is-it-wrong-to-place-the-script-tag-after-the-body-tag

They say:
>It won't validate outside of the <body> or <head> tags. It also won't make much difference
×

Success!

Help @Descartes spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.13,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...