gpt4 book ai didi

javascript - 这段代码中异步发生的方式令人困惑

转载 作者:行者123 更新时间:2023-11-28 12:12:50 26 4
gpt4 key购买 nike

我是 JS 新手,正在学习回调以及回调如何实现异步。我在 https://javascript.info/callbacks 上发现了代码这是

function loadScript(src) {
let script = document.createElement('script');
script.src = src;
document.head.append(script);
}

loadScript('/my/script.js');
// the code below loadScript doesn't wait for the script loading to finish
// ...

所以,据说 loadScript 函数是异步执行的,但为什么呢?据我所知,异步发生在通过事件循环执行的 setTimeOut 或 xhr 对象等函数中。那么,为什么我们只在loadScript函数中创建元素,它是异步执行的

最佳答案

文章的措辞写得不好。

The function is called “asynchronously,” because the action (script loading) finishes not now, but later.

函数调用是同步的。 /my/script.js 的加载是异步的,因为 JS 不会等待文件加载后再继续其调用堆栈。使用 createElement 创建的任何 script 元素都会异步加载 - 您可以阅读有关它的更多信息 here :

Dynamically inserted scripts (using document.createElement()) load asynchronously by default

下面是异步调用的一个更好的例子:

let script = document.createElement('script');

script.src = '/my/script.js';
document.head.append(script);

script.onload = function()
{
// Any code defined inside here is now truly asynchronous.
// It will not be called until /my/script.js has been loaded.
}

关于javascript - 这段代码中异步发生的方式令人困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57159548/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com