HTML defer 属性是一个布尔属性,它指定脚本在解析页面的同时下载,并在解析页面后执行。
它仅用于外部脚本(仅当存在 src 属性时才应使用)。换言之,当您在 script 标签中使用 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 属性。
<!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>
支持的浏览器
浏览器 | ![]() |
![]() |
![]() |
![]() |
![]() |
---|---|---|---|---|---|
是否支持 | 18.0 | 10.0 | 3.6 | 6.0 | 15.0 |