
requirejs
RequireJS 是一个JavaScript模组载入器。它非常适合在浏览器中使用,但它也可以用在其他脚本环境,就像 Rhino and Node。使用RequireJS载入模组化脚本将提高代码的载入速度和质量。
浏览器的兼容情况如下:
IE 6+ .......... 兼容 ✔
Firefox 2+ ..... 兼容 ✔
Safari 3.2+ .... 兼容 ✔
Chrome 3+ ...... 兼容 ✔
Opera 10+ ...... 兼容 ✔
最新版本: 2.3.11
基本介绍
- 中文名:requireJS
- 外文名:requireJS
开始使用 REQUIREJS
- 获取 RequireJS
- 添加 RequireJS
- 最佳化
注意: 如果你使用 jQuery, 这里是针对 jQuery 的教程
获取 REQUIREJS 1
去下载页面下载档案。
添加 REQUIREJS
注意: 关于 jQuery 集成的意见, 请看jQuery 集成页面
假定你的项目中 JavaScript 都放在一个 "scripts" 目录。 例如, 你的项目中有一个 project.html 页面和一些 scripts, 目录布局如下:
- 项目目录/
- util.js
- main.js
- helper/
- project.html
- scripts/
添加 require.js 到 scripts 目录, 如下:
- 项目目录/
- util.js
- main.js
- require.js
- helper/
- project.html
- scripts/
为了充分利用的最佳化工具,建议您将所有的scripts放到的HTML外面, 然后只引用 require.js 来请求载入你其它的scripts:
<!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>
在 main.js, 你可以使用 require() 来载入所有你需要运行的scripts. 这可以确保你所有的scripts都是在这里载入的, 你可以指定 data-main script 使用异步载入.
require(["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 文档去了解更多相关定义和模组的使用
最佳化 3
如果你最终决定在你在代码中使用, 可以使用最佳化结合 JavaScript 档案来减少载入时间. 在上面的例子中, 你可以结合 main.js 和 helper/util.js 加到一个档案中.