HTML async 属性是一个 Boolean 属性,用于指定脚本在加载后立即执行。
它类似于 HTML 中的 defer 属性。众所周知,async 属性是一个布尔属性,如果存在于 <script> 元素中,则返回 true 和 JavaScript,否则它将返回 false。
async 和 defer 的区别在于,async 属性允许脚本在加载后立即运行,而不会阻塞网页上的其他元素。另一方面,defer 属性允许脚本仅在页面完成加载后执行。
语法
<script async></script>
适用于
下面列出的元素允许使用 HTML async 属性。
元素 | 描述 |
---|---|
<script> | HTML<script>标签用于向HTML文档添加javascript代码。 |
HTML async 属性的示例
以下代码演示了 async 属性的用法。
带有脚本标签的 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...")
检查当前脚本中是否存在异步
考虑到另一种情况,我们将运行脚本以检查脚本标签中是否存在属性。
<!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>
支持的浏览器
浏览器 | ![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|---|
是否支持 | Yes | 10.0 | 3.6 | Yes | Yes |