The Best Position To Load JavaScript File In HTML Document

Harry: Hey Rony, have you ever wondered about the position of the JavaScript file in the HTML document ??
Rony: Nope!! But I concerned about the page speed??
Harry: The position of JavaScript file can make huge difference in the term of page speed.
Like if we opt for load script file first and then parse the rest of the HTML document, it will show the blank loading page until the script completes its loading and execution.
Rony: Ok, can you elaborate on this??
Harry: Yes, Let’s dive into it,
Rony: So, how many positions available in HTML document to insert JavaScript file??
Positions availables an HTML document
Harry: Well, mainly it’s three, in the head, in between the <body> and before the closing of the </body> tag.
We can say that in the head, body and in footer.
Rony: But what’s the difference??
Harry: Ok, let’s understand with the help of these graphics.
Script added in head

If we have added Script into the head tag, it will load, and execute first then go for HTML parsing.
Script added before the closing tag of body

But if we add it to the footer means before the closing </body> tag, then it will parse all the HTML content first and then load, and execute the script file. So, we have to clear our priority.
Got it!!
Rony: Yeah!! And I am excited to know more.
Now, still fetching script is consuming extra time which will lead the script execution delay. What about this?
Script Attributes
Async
Harry: Ok, another option is async, this is a Boolean attribute which can help us to load script asynchronously and then execute it synchronously. It will reduce the time of fetching script and help to execute script faster.

Rony: Cool!! And this attribute can affect only in the head, not in the footer before closing </body>. Right??
Harry: yes.
Rony: I have one last question like I want to parse the whole HTML page first and then want to execute the script file. Right!!
Harry: hm hm…
Rony: But I can’t add script at the end of HTML page because there, async will be useless and it will take both times fetching and execution.
Harry: ok, I got it.
Defer
So, you can use defer attribute here which is again a Boolean attribute. It will work like this:

Here, you can add script file in the head with defer attribute and then it will load asynchronously and execute at the end of the HTML page.
Here, you need to identify your requirement of the script. Like if something that you want to load before the HTML Dom you can add script in the head tag like jQuery file.
But if you need to use DOM element in the script, you have to wait for the loading of the document.
In this case, you can load your script before the end of the body tag, means in the footer.
4 thoughts on “The Best Position To Load JavaScript File In HTML Document”