[英]If I use async in my script tag in index.html do I need to bother with writing async code in scripts.js? I am asking for javascript
I am new to JavaScript.我是 JavaScript 新手。 I have learned that I can make my scripts async by putting the word async in front in the html script tag.
我了解到我可以通过将 async 这个词放在 html 脚本标记的前面来使我的脚本异步。
<!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?有什么区别吗?
These 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.脚本标签上的
async
属性意味着脚本不会被渲染阻塞 - 浏览器不会等待脚本有效负载完成下载并在继续渲染 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) (如果您在 script 标签下没有更多内容,则该属性实际上并没有做任何有用的事情)
In contrast, using the async
keyword in front of JavaScript functions will mean相反,在 JavaScript 函数前面使用
async
关键字将意味着
await
inside the async function to resolve other Promises in a clean, syntactically flat way, without .then
await
以干净、语法平坦的方式解析其他 Promise,而无需.then
They're quite different uses of the same word, async
.它们是同一个词
async
的完全不同的用法。 You may want to use the async attribute, or you may want to use async functions in some situations, or both, or neither.您可能想要使用 async 属性,或者您可能想要在某些情况下使用异步函数,或者两者都使用,或者两者都不使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.