defer VS async

本文探讨了HTML中script标签的defer与async属性的作用及差异。这两种属性允许浏览器并行下载JavaScript文件,同时不会阻塞页面解析过程。defer确保脚本按顺序执行,而async则在下载完成后立即执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[quote]
The defer Attribute

The defer attribute makes a solemn promise to the browser. It states that your JavaScript does not contain any document.write or DOM modification nastiness:

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

The browser will begin to download file.js and other deferred scripts in parallel without stopping page processing.defer was implemented in Internet Explorer version 4.0 — over 12 years ago! It’s also been available in Firefox since version 3.5.While all deferred scripts are guaranteed to run in sequence, it’s difficult to determine when that will occur. In theory, it should happen after the DOM has completely loaded, shortly before the DOMContentLoaded event. In practice, it depends on the OS and browser, whether the script is cached, and what other scripts are doing at the time.
The async Attribute

async has been introduced in HTML5:

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

async is identical to defer, except that the script executes at the first opportunity after download (an optional onload attribute can be added to run a specific function). You can’t guarantee that scripts will execute in sequence, but they will have loaded by the time the window onload event fires.There’s support for async in Firefox 3.6, Opera 10.5, and the latest WebKit build, so it should appear in the next versions of Chrome and Safari. IE9 is yet to support async, but the IE team could easily add it as an alias for defer. You can use both async and defer to support all browsers — even IE4.Perhaps within a few months, we’ll finally have a native, non-blocking JavaScript loading method that works in all browsers.

[/quote]
https://developer.mozilla.org/en-US/docs/HTML/Element/script
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值