參考來源:http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/
Asynchronous and deferred JavaScript execution explained
The HTML <script> element allows you to define when the JavaScript code in your page should start executing. The “async” and “defer” attributes were added to WebKit early September. Firefox has been supporting them quite a while already. Does your browser support the attributes?
- Normal execution <script>
- This is the default behavior of the <script> element. Parsing of the HTML code pauses while the script is executing. For slow servers and heavy scripts this means that displaying the webpage will be delayed.
- Deferred execution <script defer>
- Simply put: delaying script execution until the HTML parser has finished. A positive effect of this attribute is that the DOM will be available for your script. However, since not every browser supports defer yet, don’t rely on it!
- Asynchronous execution <script async>
- Don’t care when the script will be available? Asynchronous is the best of both worlds: HTML parsing may continue and the script will be executed as soon as it’s ready. I’d recommend this for scripts such as Google Analytics.
根據上面英文原文重點整理,重述script標籤的三種屬性:
- <script>
- <script defer>
- <script async>
上圖當中出現三個名詞:parser|net|execution
- net 代表下載該javascript檔案的時段
- execution 代表執行該javascript檔案的時段
- parser代表http client 解析的過程的時段
可以看到async的屬性相當在設計網頁場景當中相當實用,parser解析時同時將下載該javascript檔案。請愛用async!
沒有留言:
張貼留言