Recommended for you: Get network issues from WhatsUp Gold. Not end users.


Some time ago to rough swept through a require.js, didn't do much, the results yesterday to see the code inside the index is silly, don't know where to look, so require and backbone learning but also intensify.

As the front end of the business is more and more heavy, so the modular programming, but JS loading sequence may bring us trouble.

Sometimes we have to solve the page block using asynchronous loading JS way, this approach often brings some uncertain factors.

In order to solve these problems, James Burke  he got a AMD (Asynchronous Module Definition asynchronous module definition) specification

Asynchronous loading module, module load does not influence the following statement execution.

We are here to learn require.js is an implementation of the AMD library, put forward to solve the problem of his:

① Implementation of JavaScript asynchronous loading, avoid page feign death

② Managing the dependencies between modules, easy to code and maintain (this is key.)

So we have to learn it require.js

A glimpse of

First take a look at our project file directory:

We wrote the first code:

Now JS needs a main like function C speech, so I in the directory of HTM to build a main.js.

1 <html xmlns=""> 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>

So we became a require project... Note that here


Main refers to the main.js, the main is the entrance function we legend.

I'll just write in main.:

alert('Knife crazy sword Chi')

Finally we have a look our page:

We saw that he introduced the main.js, but is asynchronous, can not be blocked.

Now we change the wording:

 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);//Print the version number 13 });

Because our JS file and HTM is not a directory, so the front of the path in the configuration directory, it will first load jQuery and load our custom test.js.

We can also write this:

 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);//Print the version number 11 });

Anyway, we finally finished the first example, we now come to a stage summary:


① Main uses the config and require, config used in the preparation of some basic parameters, commonly used: path,baseUrl

② Require the first parameter is an array, the array project for the module name, they will turn loads, there is a certain order

Little actual contact with define

We are here to do a test, the original is not to write a picture lazy loading things, we use the require to try:

The structure of HTML:

 1 <html xmlns="">  2 <head>  3     <title></title>  4     <style>  5         img { min-height: 100px; min-width: 100px; border: 1px solid gray; padding: 1px; margin: 10px; }  6         #con { width: 600px; height: 400px; overflow: auto; }  7     </style>  8 </head>  9 <body> 10     <div id="con"> 11         <img src="" lazy-src=""><img 12             src="" lazy-src=""><img 13                 src="" lazy-src=""><img 14                     src="" lazy-src=""><img 15                         src="" lazy-src=""><img 16                             src="" lazy-src=""><img 17                                 src="" lazy-src=""><img 18                                     src="" lazy-src=""><img 19                                         src="" lazy-src=""><img 20                                             src="" lazy-src=""><img 21                                                 src="" lazy-src=""><img 22                                                     src="" lazy-src=""><img 23                                                         src="" lazy-src=""><img 24                                                             src="" lazy-src=""><img 25                                                                 src="" lazy-src=""><img 26                                                                     src="" lazy-src=""><img 27                                                                         src="" lazy-src=""><img 28                                                                             src="" lazy-src=""><img 29                                                                                 src="" lazy-src=""><img 30                                                                                     src="" lazy-src=""><img 31                                                                                         src="" lazy-src=""><img 32                                                                                             src="" lazy-src=""><img 33                                                                                                 src="" lazy-src=""><img 34                                                                                                     src="" lazy-src=""><img 35                                                                                                         src="" lazy-src=""><img 36                                                                                                             src="" lazy-src=""><img 37                                                                                                                 src="" lazy-src=""><img 38                                                                                                                     src="" lazy-src=""><img 39                                                                                                                         src="" lazy-src=""><img 40                                                                                                                             src="" lazy-src=""><img 41                                                                                                                                 src="" lazy-src=""><img 42                                                                                                                                     src="" lazy-src=""><img 43                                                                                                                                         src="" lazy-src=""><img 44                                                                                                                                             src="" lazy-src=""><img 45                                                                                                                                                 src="" lazy-src=""><img 46                                                                                                                                                     src="" lazy-src=""><img 47                                                                                                                                                         src="" lazy-src=""><img 48                                                                                                                                                             src="" lazy-src=""><img 49                                                                                                                                                                 src="" lazy-src=""><img 50                                                                                                                                                                     src="" lazy-src=""><img 51                                                                                                                                                                         src="" lazy-src=""><img 52                                                                                                                                                                             src="" lazy-src=""><img 53                                                                                                                                                                                 src="" lazy-src=""><img 54                                                                                                                                                                                     src="" lazy-src=""><img 55                                                                                                                                                                                         src="" lazy-src=""><img 56                                                                                                                                                                                             src="" lazy-src=""><img 57                                                                                                                                                                                                 src="" lazy-src=""><img 58                                                                                                                                                                                                     src="" lazy-src=""><img 59                                                                                                                                                                                                         src="" lazy-src=""><img 60                                                                                                                                                                                                             src="" lazy-src=""><img 61                                                                                                                                                                                                                 src="" lazy-src=""><img 62                                                                                                                                                                                                                     src="" lazy-src=""><img 63                                                                                                                                                                                                                         src="" lazy-src=""><img 64                                                                                                                                                                                                                             src="" lazy-src=""><img 65                                                                                                                                                                                                                                 src="" lazy-src=""><img 66                                                                                                                                                                                                                                     src="" lazy-src=""><img 67                                                                                                                                                                                                                                         src="" lazy-src=""><img 68                                                                                                                                                                                                                                             src="" lazy-src=""><img 69                                                                                                                                                                                                                                                 src="" lazy-src=""><img 70                                                                                                                                                                                                                                                     src="" lazy-src=""><img 71                                                                                                                                                                                                                                                         src="" lazy-src=""><img 72                                                                                                                                                                                                                                                             src="" lazy-src=""><img 73                                                                                                                                                                                                                                                                 src="" lazy-src=""><img 74                                                                                                                                                                                                                                                                     src="" lazy-src=""><img 75                                                                                                                                                                                                                                                                         src="" lazy-src=""><img 76                                                                                                                                                                                                                                                                             src="" lazy-src=""><img 77                                                                                                                                                                                                                                                                                 src="" lazy-src=""><img 78                                                                                                                                                                                                                                                                                     src="" lazy-src=""><img 79                                                                                                                                                                                                                                                                                         src="" lazy-src=""><img 80                                                                                                                                                                                                                                                                                             src="" lazy-src=""><img 81                                                                                                                                                                                                                                                                                                 src="" lazy-src=""><img 82                                                                                                                                                                                                                                                                                                     src="" lazy-src=""><img 83                                                                                                                                                                                                                                                                                                         src="" lazy-src=""><img 84                                                                                                                                                                                                                                                                                                             src="" lazy-src=""><img 85                                                                                                                                                                                                                                                                                                                 src="" lazy-src=""><img 86                                                                                                                                                                                                                                                                                                                     src="" lazy-src=""><img 87                                                                                                                                                                                                                                                                                                                         src="" lazy-src=""><img 88                                                                                                                                                                                                                                                                                                                             src="" lazy-src=""><img 89                                                                                                                                                                                                                                                                                                                                 src="" lazy-src=""><img 90                                                                                                                                                                                                                                                                                                                                     src="" lazy-src=""><img 91                                                                                                                                                                                                                                                                                                                                         src="" lazy-src=""><img 92                                                                                                                                                                                                                                                                                                                                             src="" lazy-src=""> 93     </div> 94     <script src="js/require.js" type="text/javascript" data-main="main"></script> 95 </body> 96 </html>


The core code:

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

Main code:

1 require.config({ 2     baseUrl: 'js' 3 }); 4  5 require(['jquery', 'test'], function ($, imgLazyLoad) { 6     imgLazyLoad($('#con')); //Picture lazy loading 7 });


 1 define(function () {  2     function imgLazyLoad(container) {  3         var imgLazyLoadTimer = null;  4         var resetImglazy = null;  5         container = container || $(window); //Need jQuery object  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[]) { 29                         imgArr[] = []; 30                     } 31                     imgArr[].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 });

Demo address, effect is similar.


Here we use a new things: define

The define parameter is an anonymous function, he will return a value, I here directly back to the function itself, and then call in the callback function.  

We can define an object in define and returns the object name then use more


Just saw a shim, so we simply add it here.

 1 shim: {  2     $: {  3         exports: 'jQuery'  4     },  5     _: {  6         exports: '_'  7     },  8     B: {  9         deps: [ 10             '_', 11             '$' 12             ], 13         exports: 'Backbone' 14     } 15 },

The shim parameter is used to solve the use of non AMD definition module loading sequence problem.

PS: This is what meaning, I still don't fully understand, or use the jQuery plugin needs first to ensure the jQuery download it? Here the back to add.

The need to translate the local

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 there are many things to learn, to learn that today temporarily, will integrate with backbone.

We now have a look back require to solve problems?

Because of our program of business by the server to front-end gradually, so our JavaScript development becomes more and more large.

We need the modular programming maintains a small unit, such as a complex logic may be divided into several JS.

Then a complex after the project may have hundreds of small files, RequireJS provides.Js compression.

A compression related knowledge and learning behind us. .

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Becky at November 14, 2013 - 1:27 AM