获取 RequireJS § 1
前往下载页面并获取该文件。
添加 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 调用来引用 require.js 加载您的脚本:
<!DOCTYPE html>
<html>
<head>
<title>My Sample Project</title>
<!-- data-main attribute tells require.js to load
scripts/main.js after require.js loads. -->
<script data-main="scripts/main" src="scripts/require.js"></script>
</head>
<body>
<h1>My Sample Project</h1>
</body>
</html>
如果您不希望加载 require.js 脚本阻塞渲染,也可以将脚本标签放在 </body> 部分的末尾。对于支持它的浏览器,您还可以添加一个async 属性到 script 标签上。
在 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 文档以了解有关定义和使用模块的更多信息。