日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

defer与async的认识

發布時間:2024/9/20 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 defer与async的认识 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

defer跟asyns都是腳本外聯文件的標簽屬性(標簽內的腳本不會執行),加了這兩個屬性其中一個那么腳本文件會異步加載執行。

首先檢查defer在瀏覽器中執行順序(檢查瀏覽器為chome,firfox,ie)

defer:

在編譯器中輸入代碼

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>defer async</title>
<style>
</style>
<script type="text/javascript">
  console.log("head內嵌js")
</script>
</head>
<body>
  <img src="../images/1.jpg" alt="1.jpg" οnlοad="console.log('img')" />
  <script type="text/javascript" src="js/defer.js" defer="defer"></script>
  <script type="text/javascript">

    window.onload = function(){

      console.log("onload")
    }

    console.log("內嵌js")
  </script>
</body>
</html>

在chome,firfox的控制臺中,輸出先后順序為

head內嵌js
內嵌js this is defer img onload 在ie的控制臺中,輸出先后順序為

head內嵌js
img
內嵌js
this is defer

onload

defer要等到dom構造好了后再執行,所以'this is defer'會最后輸出(上一篇文章對ie dom構造的理解是,dom中的所有資源下載后才能算構造好dom,不知道對不對?) 注:ie10中'內嵌js'先于'img'; 從瀏覽器的輸出結果可以看出,加defer的外聯標簽加載的文件,會在dom樹構成后執行,onload是在dom樹構成后并且所有資源(包括圖片css,js)加載到瀏覽器后再執行。但會在document的DOMContentLoaded事件之前。
在w3c上看到,支持defer的瀏覽器有:

Browser Support

????

The defer attribute is supported in all major browsers.

Note:?The defer attribute is not supported in Opera 12 and earlier versions. async: 這個屬性跟defer一樣,異步下載資源,不會堵塞瀏覽器渲染頁面,然而這個屬性跟defer不同的是,當該文件加載完后會立即執行該外聯文件里面的腳本,不用等到dom樹構造好。同時,幾個加async的腳本下載后,按照先到先執行的順序,不會按代碼中的排列順序執行,這點跟defer不一樣.

Browser Support

????

The async attribute is supported in Internet Explorer 10, Firefox, Opera, Chrome, and Safari.

Note:?The async attribute of the <script> tag is not supported in Internet Explorer 9 and earlier versions.

轉載于:https://www.cnblogs.com/outside/p/3723722.html

總結

以上是生活随笔為你收集整理的defer与async的认识的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。