当看到一个新的事物时,总是好奇它有什么样的功能,能做什么?如何去做?原理是什么?本文就是围绕这三点展开的。先一点一点的说吧,一下我也讲不完。
RequireJS能做什么?
- RequireJS最大亮点就是能动态加载文件,不仅仅js文件,普通css,html,txt等等,只要是文件都能加载!这点很亮吧?能加载文件有什么好的?可以按需加载文件,实现网络最优加载
- 进行项目目录、依赖管理
- 项目合并优化等等
今天整理了下目录结构对后期的规划有了进一步的明确,目前正在校对RequireJS 2.1.8 中文API的翻译事宜,又抽空看了下Google的NaCl,能够使用本地的Native Client,这个倒是不错,但是必须运行在chrome上,明年就不在支持NPAPI了,哎
RequireJS的错误机制看了部分,有全局和局部控制,使用起来还是比较方便的。
RequireJs中的插件机制也不错,可以自定义加载器插件,比如说文件加载,国际化文件加载等等。这里插件的加载原理其实很简单,自定义一个匿名模块,其中onload接口必须要实现,其他都是辅助的
最经一段时间把RequireJS的API & plugin部分做了一份翻译,目前翻译工作已完成,稍后上传上来。供大家指点。
下一步计划是,研究RequireJS的源码分析和内部机制。
贴一段RequireJS的程序入口和结束片段。
/**
* Main entry point.
*
* If the only argument to require is a string, then the module that
* is represented by that string is fetched for the appropriate context.
*
* If the first argument is an array, then it will be treated as an array
* of dependency string names to fetch. An optional function callback can
* be specified to execute when all of those dependencies are available.
*
* Make a local req variable to help Caja compliance (it assumes things
* on a require that are not standardized), and to give a short
* name for minification/local scope use.
*/
req = requirejs = function (deps, callback, errback, optional) {...}
/**
* Executes the text. Normally just uses eval, but can be modified
* to use a better, environment-specific call. Only used for transpiling
* loader plugins, not for plain JS modules.
* @param {String} text the text to execute/evaluate.
*/
req.exec = function (text) {
/*jslint evil: true */
return eval(text);
};