HTML - async 屬性



HTML 的 **async** 屬性是一個布林屬性,用於指定指令碼在載入後立即執行。

它類似於 HTML 中的 defer 屬性。眾所周知,async 屬性是一個布林屬性,如果存在於 <script> 元素中,則使用 JavaScript 返回 true,否則返回 false。

async 和 defer 之間的區別在於,async 屬性允許指令碼在載入後立即執行,而不會阻塞網頁上的其他元素。另一方面,defer 屬性允許指令碼僅在頁面載入完成後執行。

語法

<script async></script>

應用於

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

元素 描述
<script> HTML <script> 標籤用於向 HTML 文件新增 JavaScript 程式碼。

HTML async 屬性示例

以下程式碼演示了 async 屬性的用法。

帶有 script 標籤的 Async 屬性

當我們執行以下指令碼時,它將在頁面載入後立即生成一個顯示警報的輸出。當用戶點選確定時,它將顯示一段文字。

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

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

<body>
   <!--HTML 'async' attribute-->
   <h3>Example of the HTML 'async' attribute</h3>
   <p>This is demo of the HTML 'async' attribute.</p>
   <!--use within the 'script' element-->
   <script src="index.js" async></script>
</body>

</html>

index.js

alert("Alert message...")

檢查當前指令碼中是否存在 async

考慮另一種情況,我們將執行指令碼以檢查屬性是否存在於 script 標籤中。

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

<head>
   <title>HTML 'async' attribute</title>
   <style>
      button {
         padding: 10px;
         width: 100px;
         cursor: pointer;
         background-color: blueviolet;
         color: white;
      }
   </style>
</head>

<body>
   <!--HTML 'async' attribute-->
   <h3>Example of the HTML 'async' attribute</h3>
   <p>This is demo of the HTML 'async' attribute.</p>
   <p>
      Click on the below button to check the 'async' 
      attribute is present within the 'script' element or not.
   </p>
   <button onclick="func()">Check</button>
   <!--use within the 'script' element-->
   <script src="index.js" id="demo" async></script>
   <script>
      function func() {
         let value = document.querySelector("#demo").async;
         alert("Is 'async' is present or not? " + value);
      }
   </script>
</body>

</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
async 是 10.0 是 3.6
html_attributes_reference.htm
廣告