require.js读书笔记 1.start
综览
ADD REQUIREJS
§ 2
注意:jquery使用方法,请见jQuery integration page
这个项目假设你将所有的javascript文件夹都放在script的目录里。例如,如果你有一个项目,包含project.html,一些scripts,那么这个项目目录结构如下所示:
- project-directory/
- project.html
- scripts/
- main.js
- helper/
- util.js
给目录中加上require.js,这个结构看起来如下
- project-directory/
- project.html
- scripts/
- main.js
- require.js
- helper/
- util.js
为了更好地使用这个优化工具,建议将html里的所有行内script都拿出来,只放一个引用require.js的script来加载文件。
<!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的时候阻塞页面渲染,你也可以把script文件放在<body>的结尾。
在某些浏览器中,你也可以添加async attribute 属性到script标签里。
在main.js里,你可以用reqiure()来加载任何你想运行的script。这个确保了script只有一个入口,虽然定义data-main这个script属性也可以异步加载你要运行的script。 the data-main script you specify is loaded asynchronously.
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 script。为了更好地运用requireJs,请参考 API docs来了解更多关于如何定义和使用模块。
OPTIMIZE§ 3
一旦你完成了开发,并且想为你的终端用户部署(deploy)你的代码,你可以用optimizer来压缩和打包你的js文件夹。在上面的那个例子中,它连接并压缩了了main.js和helper/util.js。

浙公网安备 33010602011771号