目录
How async works
How defer works
When to use which
A quick comparison summary
首页 web前端 H5教程 说明HTML5中脚本的'异步”和' defer”属性。

说明HTML5中脚本的'异步”和' defer”属性。

Jul 13, 2025 am 03:06 AM
html5 脚本

async和defer的区别在于脚本执行时机。async让脚本并行下载且下载完立即执行,不保证执行顺序;defer则在HTML解析完成后按顺序执行脚本。两者都避免阻塞HTML解析。使用async适用于独立脚本如分析代码;defer适合需访问DOM或依赖其他脚本的场景。

Explain the `async` and `defer` attributes for scripts in HTML5.

When you're adding JavaScript to an HTML page, using the async or defer attributes can make a real difference in how your page loads and performs. These two attributes control how the browser handles script loading and execution, especially during the parsing of the HTML document.

Explain the `async` and `defer` attributes for scripts in HTML5.

Here’s what they do in short:

  • async makes the script load in parallel with HTML parsing and executes it as soon as it's downloaded — without waiting for the HTML parsing to finish.
  • defer also loads the script while HTML is being parsed, but it waits until the entire HTML document is parsed before running the script.

Let’s go into more detail about when and why you’d use each one.

Explain the `async` and `defer` attributes for scripts in HTML5.

What happens without async or defer

By default, when the browser encounters a <script></script> tag (without any attribute), it stops parsing the HTML. It downloads and runs the script immediately. Only after the script finishes executing does the browser continue building the DOM.

This behavior can cause delays in rendering the page, especially if the script is large or takes time to download. That’s why async and defer were introduced — to avoid blocking the parser.

Explain the `async` and `defer` attributes for scripts in HTML5.

How async works

The async attribute tells the browser that the script doesn’t depend on the rest of the page content or other scripts. So the browser can:

  • Download the script in the background while it continues parsing HTML
  • Run the script as soon as it finishes downloading
  • Stop HTML parsing just long enough to execute the script

Because of this behavior, async is best used for scripts that are completely independent — like analytics trackers or simple widgets that don’t interact with the page content.

Example:

<script src="analytics.js" async></script>

Important notes:

  • The order of execution isn’t guaranteed for multiple async scripts
  • They run as soon as they’re ready, not in the order they appear in the HTML

How defer works

With defer, the script also downloads in the background during HTML parsing. But instead of running right away, it waits until the entire HTML document has been parsed.

This means:

  • HTML parsing continues uninterrupted
  • Scripts are executed in the order they appear in the document
  • Execution happens after the DOM is fully built but before the DOMContentLoaded event

This is ideal for scripts that need to access or manipulate the DOM, or rely on other deferred scripts.

Example:

<script src="main.js" defer></script>

Key points:

  • defer preserves execution order
  • It ensures the DOM is ready when the script runs
  • No need to manually wait for DOMContentLoaded inside the script

When to use which

Choosing between async and defer depends on what the script does and whether it relies on anything else.

Use async if:

  • The script doesn't depend on the DOM or other scripts
  • You want it to run as soon as possible after download
  • It's something like a tracking code or third-party widget

Use defer if:

  • The script needs to access or modify the DOM
  • It relies on other scripts (especially those earlier in the page)
  • You want to ensure execution happens in a specific order

If a script is small and critical, sometimes it's even better to inline it in a <script></script> block rather than load it externally — but that's another topic.


A quick comparison summary

Feature Regular Script async defer
Blocks HTML parsing? Yes No No
Executes in order? N/A No Yes
Waits for HTML? No Yes
Waits for other scripts? No Yes (in order)

So, basically, pick async when the script can run anytime, and defer when it needs to wait for the page. Both help improve performance by avoiding render-blocking JavaScript — and that makes for a better user experience.

That’s it. Not too complicated once you get the hang of it.

以上是说明HTML5中脚本的'异步”和' defer”属性。的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Laravel 教程
1604
29
PHP教程
1510
276
如何编写基本的HTML5页模板? 如何编写基本的HTML5页模板? Jul 26, 2025 am 07:23 AM

声明文档为HTML5,避免浏览器进入怪异模式;2.定义根元素并指定语言以提升可访问性和SEO;3.中包含确保正确字符编码,实现响应式设计,设置页面标题;4.放置所有可见内容,可选添加CSS、favicon和JavaScript链接;该模板结构完整、兼容现代浏览器,适用于任何新HTML文件。

使用html5 schema.org标记定义自定义词汇。 使用html5 schema.org标记定义自定义词汇。 Jul 31, 2025 am 10:50 AM

Schema.org标记是通过语义标签(如itemscope、itemtype、itemprop)帮助搜索引擎理解网页内容的结构化数据格式;其可用于定义自定义词汇表,方法包括扩展已有类型或使用additionalType引入新类型;实际应用中应保持结构清晰、优先使用官方属性、测试代码有效性、确保自定义类型可访问;注意事项包括接受部分支持、避免拼写错误、选择合适格式如JSON-LD。

如何使用脚本将作曲家事件连接到作曲家事件? 如何使用脚本将作曲家事件连接到作曲家事件? Jul 26, 2025 am 07:52 AM

要运行自定义逻辑可使用Composer脚本,先在composer.json中添加scripts块并绑定事件。主要步骤为:1.了解Composer内置事件如pre-install-cmd、post-install-cmd等;2.设置scripts区块,按需指定命令或脚本数组,按顺序执行;3.使用类处理实现更复杂控制,通过静态方法接收Event与IO接口;4.测试时手动运行Composer命令并检查输出与返回码确保脚本正常工作。

HTML5解析器如何处理错误? HTML5解析器如何处理错误? Aug 02, 2025 am 07:51 AM

HTML5parsershandlemalformedHTMLbyfollowingadeterministicalgorithmtoensureconsistentandrobustrendering.1.Formismatchedorunclosedtags,theparserautomaticallyclosestagsandadjustsnestingbasedoncontext,suchasclosingabeforeaandreopeningitafterward.2.Withimp

什么是HTML5数据属性? 什么是HTML5数据属性? Aug 06, 2025 pm 05:39 PM

HTML5dataattributesarecustom,validHTMLattributesusedtostoreextrainformationinelementsforJavaScriptorCSS.1.Theyaredefinedasdata-*attributes,likedata-user-id="123".2.Theyallowembeddingprivate,customdatadirectlyinmarkupwithoutaffectinglayoutor

如何显示HTML5视频的控件? 如何显示HTML5视频的控件? Jul 26, 2025 am 08:11 AM

要显示HTML5视频的播放控制,必须添加controls属性;1.在标签中加入controls属性即可显示默认播放、暂停、音量、进度条、全屏等控制;2.如需自定义控制显示,可用JavaScript动态设置video.controls为true或false;3.默认控件样式因浏览器和操作系统而异,若需完全自定义界面,需移除controls并用JavaScript构建自定义控件,添加controls属性是实现播放控制的基本且必要步骤。

HTML5中的和有什么区别? HTML5中的和有什么区别? Aug 04, 2025 am 11:02 AM

请明确您想比较的两个HTML5元素或属性,例如与、与,或id与class,以便我提供清晰实用的差异解释。

如何使用HTML5将图像添加到网页上? 如何使用HTML5将图像添加到网页上? Jul 27, 2025 am 02:46 AM

在网页中添加图片的核心方法是使用标签并配合必要的属性。首先,使用自闭合的标签,并通过src属性指定图片路径,alt属性提供替代文字;其次,可通过标签包裹图片实现点击跳转;再次,使用HTML5新增的与标签结构化展示图片及标题;此外,可设置width、height或用CSS控制图片尺寸,并通过loading="lazy"实现延迟加载以优化性能。

See all articles