HTML5’s async 属性

HTML5 引入 async 属性,允许开发者在不阻塞页面加载的情况下异步加载 JavaScript 脚本,显著提升网站性能。

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

 

 

One of the big reasons I'me excited about HMTL5 is that features are being implemented that have been long overdue.  We've been using placeholders forever but we've needed to use JavaScript to do it.  We've been making entire blocks clickable like links but we've needed to use JavaScript to do it.  WebKit recently implemented HTML5's async attribute for SCRIPT tags.  We've been accomplishing this task with a variety of JavaScript hacks but this new attribute will allow us to prevent blocking in an easy way.

async - The HTML

As I mentioned above, it's as easy as adding an attribute:

<script async src="siteScript.js" onload="myInit()"></script>

The truth is that if you write your JavaScript effectively, you'll use the async attribute to 90% of your SCRIPT elements.

defer - The HTML

Safari has also added a defer attribute:

<script defer src="siteScript.js" onload="myInit()"></script>

Very similar to the async assignment.

async & defer - What's the Difference

This WebKit blog post explains the difference between defer and async best:

Both async and defer scripts begin to download immediately without pausing the parser and both support an optional onload handler to address the common need to perform initialization which depends on the script. The difference between asyncand defer centers around when the script is executed. Each async script executes at the first opportunity after it is finished downloading and before the window’s load event. This means it’s possible (and likely) that async scripts are not executed in the order in which they occur in the page. The defer scripts, on the other hand, are guaranteed to be executed in the order they occur in the page. That execution starts after parsing is completely finished, but before the document’s DOMContentLoadedevent.

Who Supports async and defer?

Also from the Safari blog:

In addition to upcoming versions of WebKit-based browsers, Firefox has long supported the defer and onload attributes and support for async was added in version 3.6. Internet Explorer has also long supported the defer attribute. While async is not yet supported, support for the onload attribute was added in version 9.

async FTW!

Seeing that WebKit had implemented async put a huge smile on my face.  Blocking is a huge bottleneck for every website and the ability to easily direct a script to load asynchronously should speed up the web!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值