HTML5’s async 属性

 

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" οnlοad="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" οnlοad="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!

发布了13 篇原创文章 · 获赞 0 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/jonathanxqs/article/details/45131551