什么是RequireJS?

/* ---

RequireJS 是一个JavaScript模块加载器。它非常适合在浏览器中使用, 它非常适合在浏览器中使用,但它也可以用在其他脚本环境, 就像 Rhino and Node. 使用RequireJS加载模块化脚本将提高代码的加载速度和质量。

IE 6+ .......... 兼容 ✔
Firefox 2+ ..... 兼容 ✔
Safari 3.2+ .... 兼容 ✔
Chrome 3+ ...... 兼容 ✔
Opera 10+ ...... 兼容 ✔

开始使用 或者看看 API

--- */

http://www.requirejs.cn/home.html

https://github.com/jrburke/requirejs

一句话, 它是为了JS模块化而生,是代码逻辑封装的手段,  目的是为了减少代码复杂度,提高代码可维护性, 满足设计上要求的高内聚+低耦合。

为浏览器环境而生,提高js加载速度。

为什么要有RequireJS?

http://www.requirejs.cn/docs/why.html

遇到的问题

  • Web sites are turning into Web apps
  • Code complexity grows as the site gets bigger
  • Assembly gets harder
  • Developer wants discrete JS files/modules
  • Deployment wants optimized code in just one or a few HTTP calls

---- 翻译 ----

1、 web站点转变为 web应用

2、代码复杂度随着站点的变大而增长

3、组装(页面代码)更加困难

4、开发者需要分离js文件和模块

5、部署活动需要优化过的代码存储在一个文件中, 或者少些HTTP请求。

解决方案:

Front-end developers need a solution with:

  • Some sort of #include/import/require
  • ability to load nested dependencies
  • ease of use for developer but then backed by an optimization tool that helps deployment

---- 翻译 ----

前端开发者需要一个满足如下条件的解决方案:

1、一些类似 include import require 等经典模块方法

2、有能力加载嵌套依赖

3、对于开发者易用, 同时也可以被(用于部署的)优化工具支持。

---- 模块化进化史 -----

原始

-在一个页面还很简单的时候, 一个同事添加了一个js函数  function xx

后由于新增需求, 另外一个同事处于另外目的, 添加了一个相同名称的函数 function xx, 内容实现不一样, 这样就悲剧了, 第一个同事实现的 函数被冲掉了, 因为它们都定义在 全局环境中。

IIFE == imediately invoked function expression  立刻执行函数表达式

组织规范要求, 每个人开发的相关内容做为一个模块, 必须放在一个IIFE的函数体中,

(fuction(){

funciton XX(){}

})();

这样两个同事开发代码都不会相互影响对方, 但是这样定义的函数, 不能再全局环境的其他代码中调用, 因为在IIFE中的函数只在其函数体中生效, 可以作为window一个属性开放出去,

但是其仍然有个缺点, 就是两个模块之间的依赖无法体现, 如果后面一个同事的开发模块, 依赖前一个同事的, 这样后面同事写的代码必须在 前一个同事代码 之后, 否则就会调用失败。

module时代

随着web页面内容越来越大, 前端代码越来越复杂,且有复杂的代码依赖关系。 就需要今天的主题事物出场。

AMD vs CommonJS

模块化标准包括 commonjs和requirejs, requireJS满足AMD标准, 为啥采用AMD?

因为主要是此标准为异步加载设计, 故适合浏览器远程加载若干模块的js文件。

而commonjs标准,加载文件为同步模式, 一个一个执行, 适合加载本地文件, nodejs实现满足此标准。

两个标准的详细描述见:

http://www.commonjs.org/

http://www.requirejs.org/docs/whyamd.html

怎么使用RequireJS?

http://requirejs.org/docs/api.html

定义模块,新建一个文件, 按照api规范定义模块实现, 模块返回为对象

//Inside file my/shirt.js:
define({
color: "black",
size: "unisize"
});

如果还有些定制逻辑,则有可以使用函数,作为模块实现作用域:

//my/shirt.js now does setup work
//before returning its module definition.
define(function () {
//Do setup work here return {
color: "black",
size: "unisize"
}
});
 

如果模块对其他模块有依赖

//my/shirt.js now has some dependencies, a cart and inventory
//module in the same directory as shirt.js
define(["./cart", "./inventory"], function(cart, inventory) {
//return an object to define the "my/shirt" module.
return {
color: "blue",
size: "large",
addToCart: function() {
inventory.decrement(this);
cart.add(this);
}
}
}
);

模块也可以返回函数

//A module definition inside foo/title.js. It uses
//my/cart and my/inventory modules from before,
//but since foo/title.js is in a different directory than
//the "my" modules, it uses the "my" in the module dependency
//name to find them. The "my" part of the name can be mapped
//to any directory, but by default, it is assumed to be a
//sibling to the "foo" directory.
define(["my/cart", "my/inventory"],
function(cart, inventory) {
//return a function to define "foo/title".
//It gets or sets the window title.
return function(title) {
return title ? (window.title = title) :
inventory.storeName + ' ' + cart.name;
}
}
);

还可以自定义模块名称

    //Explicitly defines the "foo/title" module:
define("foo/title",
["my/cart", "my/inventory"],
function(cart, inventory) {
//Define foo/title object in here.
}
);

DEMO

定义了两个模块, 和一个app, 依赖两个模块, 调用并执行:

https://github.com/fanqingsong/code-snippet/tree/master/web

one.js

//Inside one.js:
define(function() {
        return function(title) {
            return console.log('one module called');
        }
    }
);

two.js

//Inside two.js:
define(function() {
        return function(title) {
            return console.log('two module called');
        }
    }
);

app.js

requirejs.config({
    //By default load any module IDs from ./
    baseUrl: './',
});

// Start the main app logic.
requirejs(['one', 'two'],
function   (one, two) {
    one();
    two();
});

demo.html

<html>
<head>
        <!--This sets the baseUrl to the "scripts" directory, and
            loads a script that will have a module ID of 'main'-->
        <script data-main="./app.js" src="./require.js"></script>
        <style>

</style>
</head>
<body>
        <h1>hello world!</h1>
</body>
</html>

打印:

RequireJS初探的更多相关文章

  1. requirejs、backbone.js配置

    requirejs初探 参考资料官网:http://requirejs.org中文译文:http://makingmobile.org/docs/tools/requirejs-api-zh reuq ...

  2. requirejs原理深究以及r.js和gulp的打包【转】

    转自:http://blog.csdn.net/why_fly/article/details/75088378 requirejs原理 requirejs的用法和原理分析:https://githu ...

  3. RequireJS源码初探

    前两天跟着叶小钗的博客,看了下RequireJS的源码,大体了解了其中的执行过程.不过在何时进行依赖项的加载,以及具体的代码在何处执行,还没有搞透彻,奈何能力不够,只能先记录一下了. RequireJ ...

  4. RequireJS 2.0初探

    就在前天晚上RequireJS发布了一个大版本,直接从version1.0.8升级到了2.0.随后的几小时James Burke又迅速的将版本调整为2.0.1,当然其配套的打包压缩工具r.js也同时升 ...

  5. 从273二手车的M站点初探js模块化编程

    前言 这几天在看273M站点时被他们的页面交互方式所吸引,他们的首页是采用三次加载+分页的方式.也就说分为大分页和小分页两种交互.大分页就是通过分页按钮来操作,小分页是通过下拉(向下滑动)时异步加载数 ...

  6. React Native初探

    前言 很久之前就想研究React Native了,但是一直没有落地的机会,我一直认为一个技术要有落地的场景才有研究的意义,刚好最近迎来了新的APP,在可控的范围内,我们可以在上面做任何想做的事情. P ...

  7. 使用 RequireJS 优化 Web 应用前端

    基于 AMD(Asynchronous Module Definition)的 JavaScript 设计已经在目前较为流行的前端框架中大行其道,jQuery.Dojo.MooTools.EmbedJ ...

  8. 初探百度F.I.S — 由工具到解决方案

    1. 前言 阅兵放假三天,我哪儿也没去,宅着看了一些东东:git命令行.svn命令以及下面的主角——百度FIS.对看过的git.svn的命令也做了一些总结,请参见:<git命令学习笔记>和 ...

  9. (转)初探Backbone

    (转)http://www.cnblogs.com/yexiaochai/archive/2013/07/27/3219402.html 初探Backbone 前言 Backbone简介 模型 模型和 ...

随机推荐

  1. Web 在线文件管理器学习笔记与总结(13)重命名文件夹(14)复制文件夹

    (13)重命名文件夹 ① 重命名文件夹通过 rename($oldname,$newname) 实现 ② 检测文件夹名是否符合规范 ③ 检测当前目录中是否存在同名文件夹名称,如果不存在则重命名成功 i ...

  2. HOSTS文件详解【win|mac】

    hosts文件是一个用于储存计算机网络中各节点信息的计算机文件.这个文件负责将主机名映射到相应的IP地址. hosts文件通常用于补充或取代网络中DNS的功能.和DNS不同的是,计算机的使用者可以直接 ...

  3. HTML Questions:Front-end Developer Interview Questions

    What's a doctype do? Instruct the browser to render the page. What's the difference between standard ...

  4. 关于Java的File.separator

    在Windows下的路径分隔符和Linux下的路径分隔符是不一样的,当直接使用绝对路径时,跨平台会暴出“No such file or diretory”的异常. 比如说要在temp目录下建立一个te ...

  5. MessageQueue 一 简单的创建和读取

    创建一个队列,并写入数据 在读取出来 using System; using System.Collections.Generic; using System.Linq; using System.M ...

  6. Android源码剖析之Framework层基础版(窗口、linux、token、Binder)

    本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处! 关于Framework,就是应用层底下的控制层,离应用层最近,总想找个机会,写写WindowMang ...

  7. 解决Eclipse启动报错Failed to create the Java Virtual Machine

    电脑:2G内存,WIN7 32位. 启动adt-bundle-windows-x86-20140702\eclipse\eclipse.exe时,报错[Failed to create the Jav ...

  8. [LeetCode] Longest Palindromic Substring(manacher algorithm)

    Given a string S, find the longest palindromic substring in S. You may assume that the maximum lengt ...

  9. margin负值

    一列li并排的时候,需要一些间距的时候,又不需要最右边或者最左边有间距. <!DOCTYPE html> <html lang="zh-CN"> <h ...

  10. LightOj1203 - Guarding Bananas(凸包求多边形中的最小角)

    题目链接:http://lightoj.com/volume_showproblem.php?problem=1203 题意:给你一个点集,求凸包中最小的角:模板题,但是刚开始的时候模板带错了,错的我 ...