/    Sign up×
Community /Pin to ProfileBookmark

Script location best practices?

I typically place my scripts in .js files and call them right after the element they are used for. I have seen people arguing that they should be in the head and called with _onload_ or be placed at the bottom of the body. What do you all think?

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@boohooOct 11.2021 — That's an excellent and very opinionated question.

I personally don't like to have entire script wrapped in *load* event. It adds extra indentation. I prefer to silently assume that the script is running when the DOM is ready.

In the past I used to prefer putting <script> just before closing the </body>. But now, as we have async and defer attributes of the <script>, I feel like they are the best. Most of the time I end up having my script in <head> and with defer attribute:

``javascript<i>
</i>&lt;head&gt;
...
&lt;script src="foo.js" defer&gt;&lt;/script&gt;
...
&lt;/head&gt;<i>
</i>
`</CODE>
This way, script runs when the DOM is ready, but it starts downloading sooner. If your page has a lot of content in the source, it actually makes quite a difference in terms of performance.

And if my script doesn't need DOM, <C>
async` is a better choice, because it runs as soon as it's downloaded, but also doesn't block rendering of the DOM when it's being downloaded.
Copy linkTweet thisAlerts:
@RikyliauthorOct 12.2021 — @boohoo#1638115 Thanks, this is an approach I was unaware of and I like it.
×

Success!

Help @Rikyli 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.5,
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: @Yussuf4331,
tipped: article
amount: 1000 SATS,

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

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...