2025-12-22 23:17:01RequireJS 入门指南

添加 RequireJS § 2

注意:有关 jQuery 的特定建议,请参阅jQuery 集成页面

此设置假设您将所有 JavaScript 文件保存在项目的“scripts”目录中。例如,如果您的项目有一个 project.html 页面和一些脚本,则目录结构可能如下所示

project-directory/

project.html

scripts/

main.js

helper/

util.js

将 require.js 添加到 scripts 目录中,使其如下所示

project-directory/

project.html

scripts/

main.js

require.js

helper/

util.js

为了充分利用优化工具,建议您将所有内联脚本保留在 HTML 之外,并仅使用如下所示的 requirejs 调用来加载脚本

My Sample Project

My Sample Project

如果您不希望加载 require.js 脚本阻塞渲染,也可以将脚本标签放在 部分的末尾。对于支持它的浏览器,您还可以向脚本标签添加async 属性。

在 main.js 内部,您可以使用 requirejs() 加载您需要运行的任何其他脚本。这确保了单一入口点,因为您指定的 data-main 脚本是异步加载的。

requirejs(["helper/util"], function(util) {

//This function is called when scripts/helper/util.js is loaded.

//If util.js calls define(), then this function is not fired until

//util's dependencies have loaded, and the util argument will hold

//the module value for "helper/util".

});

这将加载 helper/util.js 脚本。要充分利用 RequireJS,请参阅API 文档以了解更多有关定义和使用模块的信息。