admin管理员组文章数量:1401629
I am new to JavaScript. I have learned that I can make my scripts async by putting the word async in front in the html script tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script async src="scripts.js"></script>
</body>
</html>
But I saw in another video that I need to use callbacks / Promises / async-await to make my code async.
const friendlyFunction = async ()=> {
return `Hello`
}
console.log(friendlyFunction)
Is there any difference?
I am new to JavaScript. I have learned that I can make my scripts async by putting the word async in front in the html script tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script async src="scripts.js"></script>
</body>
</html>
But I saw in another video that I need to use callbacks / Promises / async-await to make my code async.
const friendlyFunction = async ()=> {
return `Hello`
}
console.log(friendlyFunction)
Is there any difference?
Share Improve this question edited Oct 14, 2022 at 6:01 starball 53.6k34 gold badges233 silver badges923 bronze badges asked Sep 2, 2021 at 6:37 MasudalimranMasudalimran 1452 silver badges11 bronze badges 1-
1
async
keyword with functions andasync
attribute onscript
tag do different things. – Yousaf Commented Sep 2, 2021 at 6:40
1 Answer
Reset to default 6These are two entirely independent concepts.
The async
attribute on a script tag means that the script will not be render-blocking - the browser will not wait for the script payload to finish downloading and to finish executing the script before continuing on to render later parts of the HTML. This would be helpful if you had other stuff below the script tag, eg
<script async src="scripts.js"></script>
<div>more HTML content here</div>
(If you don't have any more content below the script tag, the attribute doesn't really do anything useful)
In contrast, using the async
keyword in front of JavaScript functions will mean
- The function will always return a Promise
- If you return a value from inside the function, the returned Promise will resolve to that value
- You can use
await
inside the async function to resolve other Promises in a clean, syntactically flat way, without.then
They're quite different uses of the same word, async
. You may want to use the async attribute, or you may want to use async functions in some situations, or both, or neither.
本文标签:
版权声明:本文标题:javascript - If I use async in my script tag in index.html do I need to bother with writing async code in scripts.js? - Stack Ov 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744240304a2596757.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论