Require.js

简介:
前言

前段时间粗略的扫过一次require.js,当时没怎么在意,结果昨天看到index里面的代码就傻了,完全不知道从哪开始看啦,所以require与backbone的学习还要加紧才行。

由于前端所占业务越来越重,所以出现了模块化编程,但是js加载的先后顺序可能会给我们带来麻烦。

有时候我们为了解决页面堵塞会采用异步加载js的方式,这种方式往往带来了一些不确定因素。

为了解决这些问题,James Burke 便搞了一个AMD(Asynchronous Module Definition 异步模块定义)规范

异步加载模块,模块加载不影响后续语句执行。

我们这里要学习的require.js就是一个实现了AMD的库,他的提出解决了以下问题:

① 实现javascript异步加载,避免页面假死

② 管理模块之间的依赖性,便于代码编写与维护(这是重点啊)

于是我们一起来学习require.js吧

惊鸿一瞥

首先看一看我们的项目文件目录:



我们写下第一段代码:

现在我们的js就需要一个像C语音的main函数,所以我在htm目录再建一个main.js吧

复制代码
1 <html xmlns="http://www.w3.org/1999/xhtml">
2 <head>
3     <title></title>
4     <script src="js/require.js" type="text/javascript" data-main="main"></script>
5 </head>
6 <body>
7 </body>
8 </html>
复制代码
这样我们就成了一个require项目啦。。。需要注意的是这里的

data-main="main"
main指的就是main.js,这个main就是我们传说中的入口函数了。

我先随便在main中写点东西:

alert('刀狂剑痴')
最后我们看看我们的页面:



我们看到他自己引入了main.js,而且是异步的,不会出现阻塞哦。

现在我们换个写法:

复制代码
 1 /// <reference path="js/require.js" />
 2 /// <reference path="js/jquery.js" />
 3 
 4 require.config({
 5     paths: {
 6         jquery: 'js/jquery',
 7         test: 'js/test'
 8     }
 9 });
10 
11 require(['jquery', 'test'], function ($) {
12     alert($().jquery);//打印版本号
13 });
复制代码


因为我们js文件与htm不是一个目录,所以前面path就在设置目录了,这里首先会加载jquery然后加载我们自定义的test.js。

我们也可以这样写:

复制代码
 1 require.config({
 2 //    paths: {
 3 //        jquery: 'js/jquery',
 4 //        test: 'js/test'
 5 //    },
 6     baseUrl: 'js'
 7 });
 8 
 9 require(['jquery', 'test'], function ($) {
10     alert($().jquery);//打印版本号
11 });
复制代码
反正最后我们完成了第一个例子,现在我们来阶段总结一番:

【阶段总结】

① main使用了config与require,config用于配制一些基本参数,常用:path、baseUrl

② require第一个参数为数组,数组项目为模块名,他们会依次加载,是有一定顺序的

小小实战接触define

我们这里来搞一个测试,原来不是写了一个图片延迟加载的东东么,我们使用require来试试:

HTML结构:

 html
核心代码:

<script src="js/require.js" type="text/javascript" data-main="main"></script>
main代码:

复制代码
1 require.config({
2     baseUrl: 'js'
3 });
5 require(['jquery', 'test'], function ($, imgLazyLoad) {
6     imgLazyLoad($('#con')); //图片延迟加载
7 });
复制代码
test.js:

复制代码
 1 define(function () {
 2     function imgLazyLoad(container) {
 3         var imgLazyLoadTimer = null;
 4         var resetImglazy = null;
 5         container = container || $(window); //需要时jquery对象
 6         var imgArr = {};
 7         initImg();
 8         lazyLoad();
 9         autoLoad();
10         container.scroll(function () {
11             lazyLoad();
12         });
13         $(window).resize(function () {
14             initImg();
15         });
16         $(document).mousemove(function () {
17             clearTimeout(imgLazyLoadTimer);
18             if (resetImglazy) clearTimeout(resetImglazy);
19             resetImglazy = setTimeout(function () {
20                 autoLoad();
21             }, 5000);
22         });
23         function initImg() {
24             $('img').each(function () {
25                 var el = $(this);
26                 if (el.attr('lazy-src') && el.attr('lazy-src') != '') {
27                     var offset = el.offset();
28                     if (!imgArr[offset.top]) {
29                         imgArr[offset.top] = [];
30                     }
31                     imgArr[offset.top].push(el);
32                 }
33             });
34         }
35         function lazyLoad() {
36             var height = container.height();
37             var srollHeight = container.scrollTop();
38             for (var k in imgArr) {
39                 if (parseInt(k) < srollHeight + height) {
40                     var _imgs = imgArr[k];
41                     for (var i = 0, len = _imgs.length; i < len; i++) {
42                         var tmpImg = _imgs[i];
43                         if (tmpImg.attr('lazy-src') && tmpImg.attr('lazy-src') != '') {
44                             tmpImg.attr('src', tmpImg.attr('lazy-src'));
45                             tmpImg.removeAttr('lazy-src');
46                         }
47                     }
48                     delete imgArr[k];
49                 }
50             }
51         } //lazyLoad
52         function autoLoad() {
53             var _key = null;
54             for (var k in imgArr) {
55                 if (!_key) {
56                     _key = k;
57                     break;
58                 }
59             }
60             var _imgs = imgArr[_key];
61             for (var i = 0, len = _imgs.length; i < len; i++) {
62                 var tmpImg = _imgs[i];
63                 if (tmpImg.attr('lazy-src') && tmpImg.attr('lazy-src') != '') {
64                     tmpImg.attr('src', tmpImg.attr('lazy-src'));
65                     tmpImg.removeAttr('lazy-src');
66                 }
67             }
68             delete imgArr[_key];
69             if (imgLazyLoadTimer) {
70                 clearTimeout(imgLazyLoadTimer);
71             }
72             imgLazyLoadTimer = setTimeout(autoLoad, 3000);
73         }
74     } //imgLazyLoad
75     return imgLazyLoad;
76 });
复制代码
演示地址,效果类似而已

http://sandbox.runjs.cn/show/7vpjps1r

【阶段总结】

这里我们使用了一个新的东西:define

define的参数是一匿名函数,他会有一个返回值,我这里直接返回了函数本身,然后在回调函数中调用之。
我们可以在define中定义一个对象然后返回对象名那么用法就更多了
补充

刚刚看到了一个shim,于是我们这里简单补充一下吧

复制代码
 1 shim: {
 2     $: {
 3         exports: 'jQuery'
 4     },
 5     _: {
 6         exports: '_'
 7     },
 8     B: {
 9         deps: [
10             '_',
11             '$'
12             ],
13         exports: 'Backbone'
14     }
15 },
复制代码
shim参数用于解决使用非AMD定义的模块载入顺序问题。

PS:这个是神马意思,我还没完全理解,大概是使用jquery插件时候需要先保证jquery下载才行吧?这里后面再补充。

需要翻译的地方

Supported configuration options:
baseUrl: the root path to use for all module lookups. So in the above example, "my/module"'s script tag will have a src="/another/path/my/module.js". baseUrl is notused when loading plain .js files (indicated by a dependency string starting with a slash, has a protocol, or ends in .js), those strings are used as-is, so a.js and b.js will be loaded from the same directory as the HTML page that contains the above snippet.
If no baseUrl is explicitly set in the configuration, the default value will be the location of the HTML page that loads require.js. If a data-main attribute is used, that path will become the baseUrl.
The baseUrl can be a URL on a different domain as the page that will load require.js. RequireJS script loading works across domains. The only restriction is on text content loaded by text! plugins: those paths should be on the same domain as the page, at least during development. The optimization tool will inline text! plugin resources so after using the optimization tool, you can use resources that reference text! plugin resources from another domain.
paths: path mappings for module names not found directly under baseUrl. The path settings are assumed to be relative to baseUrl, unless the paths setting starts with a "/" or has a URL protocol in it ("like http:"). Using the above sample config, "some/module"'s script tag will be src="/another/path/some/v1.0/module.js".
The path that is used for a module name should not include an extension, since the path mapping could be for a directory. The path mapping code will automatically add the .js extension when mapping the module name to a path. If require.toUrl() is used, it will add the appropriate extension, if it is for something like a text template.
When run in a browser, paths fallbacks can be specified, to allow trying a load from a CDN location, but falling back to a local location if the CDN location fails to load.
shim: Configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value.
Here is an example. It requires RequireJS 2.1.0+, and assumes backbone.js, underscore.js and jquery.js have been installed in the baseUrl directory. If not, then you may need to set a paths config for them:
requirejs.config({
    //Remember: only use shim config for non-AMD scripts,
    //scripts that do not already call define(). The shim
    //config will not work correctly if used on AMD scripts,
    //in particular, the exports and init config will not
    //be triggered, and the deps config will be confusing
    //for those cases.
    shim: {
        'backbone': {
            //These script dependencies should be loaded before loading
            //backbone.js
            deps: ['underscore', 'jquery'],
            //Once loaded, use the global 'Backbone' as the
            //module value.
            exports: 'Backbone'
        },
        'underscore': {
            exports: '_'
        },
        'foo': {
            deps: ['bar'],
            exports: 'Foo',
            init: function (bar) {
                //Using a function allows you to call noConflict for
                //libraries that support it, and do other cleanup.
                //However, plugins for those libraries may still want
                //a global. "this" for the function will be the global
                //object. The dependencies will be passed in as
                //function arguments. If this function returns a value,
                //then that value is used as the module export value
                //instead of the object found via the 'exports' string.
                //Note: jQuery registers as an AMD module via define(),
                //so this will not work for jQuery. See notes section
                //below for an approach for jQuery.
                return this.Foo.noConflict();
            }
        }
    }
});

//Then, later in a separate file, call it 'MyModel.js', a module is
//defined, specifying 'backbone' as a dependency. RequireJS will use
//the shim config to properly load 'backbone' and give a local
//reference to this module. The global Backbone will still exist on
//the page too.
define(['backbone'], function (Backbone) {
  return Backbone.Model.extend({});
});
In RequireJS 2.0.*, the "exports" property in the shim config could have been a function instead of a string. In that case, it functioned the same as the "init" property as shown above. The "init" pattern is used in RequireJS 2.1.0+ so a string value for exports can be used forenforceDefine, but then allow functional work once the library is known to have loaded.
For "modules" that are just jQuery or Backbone plugins that do not need to export any module value, the shim config can just be an array of dependencies:
requirejs.config({
    shim: {
        'jquery.colorize': ['jquery'],
        'jquery.scroll': ['jquery'],
        'backbone.layoutmanager': ['backbone']
    }
});
Note however if you want to get 404 load detection in IE so that you can use paths fallbacks or errbacks, then a string exports value should be given so the loader can check if the scripts actually loaded (a return from init is not used for enforceDefine checking):
requirejs.config({
    shim: {
        'jquery.colorize': {
            deps: ['jquery'],
            exports: 'jQuery.fn.colorize'
        },
        'jquery.scroll': {
            deps: ['jquery'],
            exports: 'jQuery.fn.scroll'
        },
        'backbone.layoutmanager': {
            deps: ['backbone']
            exports: 'Backbone.LayoutManager'
        }
    }
});
Important notes for "shim" config:
The shim config only sets up code relationships. To load modules that are part of or use shim config, a normal require/define call is needed. Setting shim by itself does not trigger code to load.
Only use other "shim" modules as dependencies for shimmed scripts, or AMD libraries that have no dependencies and call define() after they also create a global (like jQuery or lodash). Otherwise, if you use an AMD module as a dependency for a shim config module, after a build, that AMD module may not be evaluated until after the shimmed code in the build executes, and an error will occur. The ultimate fix is to upgrade all the shimmed code to have optional AMD define() calls.
The init function will not be called for AMD modules. For example, you cannot use a shim init function to call jQuery's noConflict. See Mapping Modules to use noConflict for an alternate approach to jQuery.
Shim config is not supported when running AMD modules in node via RequireJS (it works for optimizer use though). Depending on the module being shimmed, it may fail in Node because Node does not have the same global environment as browsers. As of RequireJS 2.1.7, it will warn you in the console that shim config is not supported, and it may or may not work. If you wish to suppress that message, you can pass requirejs.config({ suppress: { nodeShim: true }});.
总结

RequireJs还有许多东西需要学习,今天暂时到这,后面学习时会与backbone整合。

我们现在再回过头看看require解决了什么问题?

因为我们程序的业务由服务器端逐步转到了前端,所以我们的javascript开发变得越发庞大了。

我们需要模块化编程维护着一个个小的单元,比如我们一个复杂的逻辑可能分为几个js。

然后一个复杂的项目结束后可能会有上百个小文件,RequireJS提供了.js进行压缩。

关于压缩相关知识我们后面点再学习啦。。。


本文转自叶小钗博客园博客,原文链接:http://www.cnblogs.com/yexiaochai/p/3213712.html,如需转载请自行联系原作者


相关文章
|
缓存 Linux 开发工具
CentOS 7- 配置阿里镜像源
阿里镜像官方地址http://mirrors.aliyun.com/ 1、点击官方提供的相应系统的帮助 :2、查看不同版本的系统操作: 下载源1、安装wget yum install -y wget2、下载CentOS 7的repo文件wget -O /etc/yum.
262250 0
|
8月前
|
前端开发 测试技术 API
2025年API开发必备:10款优秀Postman替代工具大盘点
API测试在现代开发中至关重要,Postman虽为首选,但市场上涌现出许多优秀替代工具。本文精选2025年10款好评如潮的API测试工具:Apifox、Insomnia、Hoppscotch、Paw、Talend API Tester、HTTPie、ARC、Swagger UI、SoapUI和Thunder Client。这些工具各具特色,满足不同需求,如团队协作、开源易用、自动化测试等。无论是简洁轻量还是功能全面,总有一款适合你的团队,助力效率提升。
3994 121
|
12月前
|
移动开发 JavaScript 前端开发
简单易用的jquery响应式轮播图插件ma5slider
ma5slider是一款简单易用的jquery响应式轮播图插件。该轮播图支持鼠标拖拽,可以通过CSS定制外观,支持无限循环模式,内置水平,垂直和淡入淡出三种轮播图过渡动画效果。
|
JSON 前端开发 JavaScript
不会webpack的前端可能是捡来的,万字总结webpack的超入门核心知识
该文章提供了Webpack的基础入门指南,涵盖安装配置、基本使用、加载器(Loaders)、插件(Plugins)的应用,以及如何通过Webpack优化前端项目的打包构建流程。
不会webpack的前端可能是捡来的,万字总结webpack的超入门核心知识
|
安全 网络安全 网络架构
OpenWRT软路由web界面如何远程访问
OpenWRT软路由web界面如何远程访问
|
JavaScript 前端开发 API
强大的图片预览组件Viewer.js
1、 Viewer.js简介 2、Viewer.js支持的功能 3、Viewer.js的API 4 使用方法 4.1 引入方式 4.2 简单demo 5.viewer.js源码,js版本
3028 0
强大的图片预览组件Viewer.js
|
Python
解决报错:jinja2.exceptions.TemplateNotFound: index.html
一、问题描述 (1)首先写了一个简单的登录账号密码的页面:
1816 0
解决报错:jinja2.exceptions.TemplateNotFound: index.html
|
SQL Go
使用CASE表达式替代SQL Server中的动态SQL
原文: 使用CASE表达式替代SQL Server中的动态SQL 翻译自: http://www.mssqltips.com/sqlservertip/1455/using-the-case-expression-instead-o...
883 0
|
7天前
|
云安全 人工智能 自然语言处理