Describe the difference between `<script...
Describe the difference between `<script...
All of these ways (<script>
, <script async>
, and <script defer>
) are used to load and execute JavaScript files in an HTML document, but they differ in how the browser handles loading and execution of the script:
<script>
is the default way of including JavaScript. The browser blocks HTML parsing while the script is being downloaded and executed. The browser will not continue rendering the page until the script has finished executing.
<script async>
downloads the script asynchronously, in parallel with parsing the HTML. Executes the script as soon as it is available, potentially interrupting the HTML parsing. <script async>
do not wait for each other and execute in no particular order.
<script defer>
downloads the script asynchronously, in parallel with parsing the HTML. However, the execution of the script is deferred until HTML parsing is complete, in the order they appear in the HTML.
Here's a table summarizing the 3 ways of loading <script>
s in a HTML document.
Here's a table summarizing the 3 ways of loading <script>
in a HTML document.
Feature | <script> |
<script async> |
<script defer> |
---|---|---|---|
Parsing behavior | Blocks HTML parsing | Runs parallel to parsing | Runs parallel to parsing |
Execution order | In order of appearance | Not guaranteed | In order of appearance |
DOM dependency | No | No | Yes(waits for DOM) |
<script>
tags are for<script>
tags are used to include JavaScript on a web page. The async and defer attributes are used to change how/when the loading and execution of the script happens.
<script>
For normal <script>
tags without any async or defer, when they are encountered, HTML parsing is blocked, the script is fetched and executed immediately. HTML parsing resumes after the script is executed. This can block rendering of the page if the script is large.
Use <script>
for critical scripts that the page relies on to render properly.
<!DOCTYPE html>
<html>
<head>
<title>Regular Script</title>
</head>
<body>
<!-- Content before the script -->
<h1>Regular Script Example</h1>
<p>This content will be rendered before the script executes.</p>
<!-- Regular script -->
<script src="regular.js"></script>
<!-- Content after the script -->
<p>This content will be rendered after the script executes.</p>
</body>
</html>
<script async>
In <script async>
, the browser downloads the script file asynchronously (in parallel with HTML parsing) and executes it as soon as it is available (potentially before HTML parsing completes). The exec...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào