gpt4 book ai didi

javascript - 数据主脚本加载和普通脚本加载之间的区别

转载 作者:可可西里 更新时间:2023-11-01 01:37:27 25 4
gpt4 key购买 nike

当使用 RequireJS 时,包含你的脚本有什么区别

<script data-main="scripts/main" src="scripts/require.js"></script>

<script src="scripts/require.js"></script>

data-main 属性在加载脚本时发生了什么变化?我有 read through the docs on this ,而我并不完全清楚其中的区别。

You will typically use a data-main script to set configuration options and then load the first application module. Note: the script tag require.js generates for your data-main module includes the async attribute. This means that you cannot assume that the load and execution of your data-main script will finish prior to other scripts referenced later in the same page.

文档中提到您通常会使用数据主脚本来设置配置选项并加载第一个应用程序模块——但您不能也通过普通的旧来做到这一点吗?脚本标签?使用 data-main 属性进行配置加载应用程序模块是否有好处?

唯一与data-main不同的是异步加载吗?或者还有更多?

最佳答案

data-main只是执行初始 require 的另一种方式调用您的应用程序。为了说明......这个:

<script data-main="scripts/main" src="scripts/require.js"></script>

等同于:

<script src="scripts/require.js"></script>
<script>require(["scripts/main"])</script>

这两种形式都是异步的。这就是它的全部内容。关于您有多少个入口点或 RequireJS 配置将位于何处的考虑与 data-main 的使用完全正交。 .换句话说,这些考虑因素在您使用 data-main 时发挥了作用。与它们在您使用 require(["scripts/main"]) 中发挥的作用完全相同.

您引用的文档部分只是通过提及加载了 data-main 的脚本来掩盖事情创建一个 script head 中的元素元素与 async属性集,因为这与通过 RequireJS 加载任何脚本没有什么不同。 RequireJS 加载的每个脚本都会有一个 script为它创建的元素,在 head 中, 并且有 async属性集。

通常使用data-main对于只有一个入口点的应用程序,并将 RequireJS 的配置放在 data-main 中指定的模块中, 但无论如何都不需要。例如,这是一个完全有效的用法:

<script>
require = {
// RequireJS config here...
};
</script>
<script data-main="scripts/main" src="scripts/require.js"></script>
<script>
require(["foo"], function (foo) {
foo.something();
});
</script>

通过设置 require 给 RequireJS 配置。在加载 RequireJS 之前在全局空间中。 (如果 require 在加载 RequireJS 之前定义,它将采用 require 的值作为其配置。)除了通过加载 scripts/main 启动应用程序之外, 此代码还加载 foo并对其调用一个方法:两个入口点。

关于javascript - 数据主脚本加载和普通脚本加载之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35027046/

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