The script tag usually uses when link external JS file to HTML file, or insert script into HTML file.
In this post, I'll write about the former one.
Include in the head Tag
This form is an old style.
<head>
...
<script src="main.js"></script>
...
</head>
How it works
First, it parses an HTML code.
If it meets the script tags, it stops the parsing.
It fetches a certain JS file and executes it.
Finally, it parses the remaining HTML code.
Pros and Cons
If you use this form, a users will be bored.
The user have to wait until all JS files are fetching and executing, and parsing HTML file is finished.
Include in the body tag
This form is a general style and improving the problem of first form.
<body>
...
<script src="main.js"></script>
</body>
How it works
It parses the whole HTML code.
Next, it fetches a certain JS file, and executes it.
Pros and Cons
A user can fastly see the screen.
But, if an HTML code depends on JS files, that's it.
There is no meaning before executing JS files.
Use async property
I can sometimes see this form.
<head>
...
<script async src="main.js"></script>
...
</head>
How it works
It parses an HTML code, and it fetches a certain JS file in parallel.
If the fetching is over, it stops the parsing HTML code, and it executes the fetched JS files.
Finally, it parses the remaining HTML code.
Pros and Cons
This form is faster than previous forms.
However, parsing HTML code is stopped when JS files are executed.
In addition to, if it is not parsed HTML code yet when the executing JS files, there will be problem in it.
Use defer property
I always use this form. I think this form is the most efficient.
<head>
...
<script defer src="main.js"></script>
...
</head>
How it works
It parses an HTML code, and it fetches a certain JS file in parallel.
It executes the fetched JS file after finishing the parsing an HTML code.
Pros and Cons
It fastly shows screen to users. Because parsing an HTML is done first, it shows the screen quickly to the user.
It fetches a specified JS files in parallel, so it doesn't waste a time.
It is more safe to execute JS codes, because it executes the JS files after finishing the parsing an HTML file.
'Web > HTML' 카테고리의 다른 글
[HTML] Emmet (0) | 2020.09.02 |
---|
댓글