HTML - defer 屬性



HTML defer 屬性是一個布林屬性,它指定指令碼與頁面解析並行下載,並在頁面解析完成後執行。

它僅用於外部指令碼(僅當存在 src 屬性時才應使用)。換句話說,當您在指令碼標籤中使用 defer 屬性時,它會告訴瀏覽器在繼續解析 HTML 文件的同時下載指令碼檔案。

如果<script>中不存在 src 屬性,則 defer 屬性不會對其產生影響。

語法

<script defer></script>

應用於

以下列出的元素允許使用 HTML defer 屬性

元素 描述
<script> HTML <script> 標籤用於將指令碼匯入 HTML 文件。

HTML defer 屬性示例

以下示例將說明 HTML defer 屬性,以及我們應該在哪裡以及如何使用此屬性!

使用 script 元素的 defer 屬性

在以下示例中,我們將使用 <script> 元素的 defer 屬性來在解析頁面的同時並行下載指令碼。

<!DOCTYPE html>
<html lang="en">

<head>
    <title>HTML 'defer' attribute</title>
</head>

<body>
    <!--HTML 'defer' attribute-->
    <h3>Example of the HTML 'defer' attribute</h3>
    <!--'defer' attribute within the script element-->
    <p>
        If the 'src' attribute is not present in
        script element, it would have no effect</p>
    <script src="index.js" defer></script>
</body>

</html>

index.js 檔案

alert("Hello world");

檢查 defer 屬性是否存在

考慮另一種情況,我們將執行 JavaScript 程式碼以檢查 defer 屬性是否存在於 script 元素中。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>HTML 'defer' attribute</title>
   <style>
      div {
         color: green;
         font-weight: bold;
         font-size: 20px;
      }

      button {
         width: 100px;
         padding: 15px;
         cursor: pointer;
         color: white;
         background-color: green;
         border: none;
         border-radius: 5px;
      }
   </style>
</head>
<body>
   <!--HTML 'defer' attribute-->
   <h3>Example of the HTML 'defer' attribute</h3>
   <!--'defer' attribute within the script element-->
   <p>If the 'src' attribute is not present in script
    element, it would have no effect</p>
   <div id='res'></div>
   <br>
   <button onclick="check()">
      Check
   </button>
   <script src="index.js" 
      id="demo" 
      defer>
      </script>
   <script>
      function check() {
         let x = document.getElementById('demo').defer;
         let res = document.getElementById('res');
         res.innerHTML = "Is the 'defer' attribute present" +
         "within the 'script' element or not? " + x;
      }
   </script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
defer 是 18.0 是 10.0 是 3.6 是 6.0 是 15.0
html_attributes_reference.htm
廣告