Record: Sea.js and Require.js configuration vs. performance

Source: Internet
Author: User

Recently a little busy, long time no blog, record the configuration of the previous configuration require.js and Sea.js. (Errors are expected to be raised


File directory

/app (Project using JS)

/lib (require.js JQ Depository)

/plugin (frame corresponding function plug-in)

Require.js the convenience is that not AMD module components can be configured with configuration files. And the asynchronous loading JS page loading speed is a lever. Of course there will be a problem, the speed is too slow, you may appear js,timeout (can be configured to resolve.)

Config.js (config file)

Configuration information Requirejs.config ({    //module Base path    baseUrl: ' Js/lib ',    //Map module name not placed directly under BASEURL    paths: {    app: ' ... /app ',    plugin: '. /plugin ',    jquery: ' Jquery-1.9.1.min ',    lazyload: '. /plugin/jquery.lazyload.min ',    base: '. /',    Controller: '. /app/controller ',    model: '. /app/model '    },    //For a module that does not use define () declares a dependency    shim: {    lazyload:{        deps: [' jquery '],        Exports: ' Lazyload '    },    ' Plugin/placeholder ': {        deps: [' jquery '],        exports: ' Placeholder '    }    },    //Set Request Timeout time long, set to 0 for unlimited timeouts    waitseconds:0});

The official document has a indexmain.js request corresponding to the Homepage JS module index.js. (probably the following feeling)

require ([' config '], function () {})

Request ([dependent module name], callback ());

require ([' config '], function () {  require ([' app/index ']);});

And then the various modules are operated on the Index.js module, initialized and so on.

define ([' jquery ',], function ($) {});

Define module ([dependent module name], callback (module return parameter variable));

define ([' jquery ',], function ($) {    $ (document). Click (function () {        alert ($);    });});

Feel a bit redundant, so the configuration is to take the direct one index.js directly request the corresponding module for index service.

require ([' config '], function () {require ([' jquery ', ' ...        /common '], function ($) {$ (document). Click (function () {alert ($);    }); });});

Requirejs also support the cmd notation (JS inside write require (* *) Request JS), forget where to read an article, Requirejs is to convert the cmd into require ([' jquery ', '. /common ']). So it's not going to be explored.


Curiosity, individual or test the use of sea.js in development. Same as module loading, because it is cmd, lazy loading mode, logical thinking more reasonable?

Personal feel sea document is more chaotic, require is more complete. Specific experience ...

File directory

/app (Project using JS Controller)


/seajs (seajs seajs configuration file)




Optimized the directory path for the last require JS dug pit

Older versions of Seajs can be <script src= "./sea.js" data-main= "./init" ></script> introduced the module controller, (the old demo will have this)

The module controller is now invoked using Seajs.use ([],function () {})

Seajs. configuration files need to be introduced using tags, <script src= "./config.js" ></script>


/** * Created by Moki on 2015-5-16. */var seaurl=location.protocol+ '//';seajs.config ({    //sea.js Base path    base:seaurl+ "/res/global /js/sea ",    //path configuration    paths: {        ' tuonews_reception ': seaurl+ '/res/app/tuonews/reception/default/js ',        ' Tuonews_user ': seaurl+ '/res/app/tuonews/user/default/js ',        ' jq ': ' jquery ',        ' jq_plugins ': ' Jquery/plugins ',        ' plugins ': ' Plugins '    ,    //alias config alias    : {        ' jquery ': ' Jq/jquery ',        ' $ ': ' Jq/jquery '    },    //debug mode    debug:true,    //File Encoding    CharSet: ' Utf-8 '});

After the introduction of Sea.js and Config.js on the page, the corresponding module controller is called.

Add the corresponding code call module to the page

Seajs.use ([' jQuery ', ' Common '],function ($) {})

Invoking a module callback

The official recommendation callback and module do not use Seajs.use to request module calls, but instead use require;

/** * Created by Moki on 2015-5-12. */define (function (require,exports,module) {//Assignment variable request module    var $ = require (' jquery ');    $ (function () {///depending on the node to determine if the corresponding JS plugin needs to be loaded var banner = $ (' #banner ');       if (Banner[0]) {require (' banner ');    Banner.banner (); }    });});

SEAJS's modular plugin needs to change the current plugin

JQ, the new JQ itself supports AMD mode, and under Seajs simply

if (typeof define = = = "function" && define.amd && define.amd.jQuery) {define ("JQuery", [], function () {return jQuery;} );}


if (typeof define = = = "function") {define ("jquery", [], function () {return jquery;});

As for the low version JQ needs to define JQ

Define (' jquery ', [],function (Require, exports, module) {//place jquery source code module.exports = jquery;});

Make cmd JQ plugin

Define (' jquery ', [],function (Require, exports, module) {        var $= require ([jquery]);//plug-in code        $.FN.A = function () {}        

Advantages and Disadvantages

Basically SEAJS and require configuration is complete; now I have problems in development;

Require due to the project operation and maintenance direction, resulting in the whole project has not been formally put into actual combat, it is estimated that there will be pits;

In the logical thinking of development,

Seajs is to take on-demand request JS, Sea's thinking will be clearer than clear, (still not compressed JS before), the controller is not many times, through a JS to control multiple pages, the advantage is that you can cache this JS file,

Requirejs, is to load the dependent files before compiling, so to multiple different pages using the same JS control, will make a lot of useless JS loading different pages, so it is necessary to split a number of JS. What happens when I take the CMD mode load module under Requirejs? (It should not be proposed in itself, but it is convenient for the transition, so it is still not being considered);

So it looks like SEAJS is better for development?

You always say Requirejs is faster than Seajs?

The SEAJS will execute the require in the module after the module is loaded, but Requirejs will execute the corresponding JS after the load is completed.

If you want to find out what's going on, please read the quote article carefully.


Http://'s talk about it. Browser Resource load Optimization

Individuals think that Yuber chat is more abstract and macroscopic, such as standards, concepts, mechanisms, communities and so on. Recently has been doing performance optimization work, on their own experience to talk about the similarities and differences between Require.js and Sea.js. The two loaders and standards do not have the pros and cons of the distinction, this point is only the difference. In particular, we have to choose according to the actual situation

Before I begin I have assumed that you are already familiar with Requirejs and Seajs grammar, if not yet, please go here:

-CMD Standard:
-AMD Standard:

Compared with require.js and sea.js, in a sense, compared to the AMD standard and the CMD standard, the individual think that the two class libraries in the module and factory writing is actually not much difference, the difference is

    • Loading of modules
    • The execution of the factory function.

Here in advance to say, if your site before the online habit of all the modules packed compression, in fact, Requirejs and Seajs are not very different.

# # Load Differences

This section please allow me to copy a post

Yuber turned a seajs and requirejs the biggest difference, this post original (not including PostScript) conclusion is

Requirejs You hang of me, this is why I do not like Requirejs reason, the pit hidden too deep.

Seajs is the correct way to load modules asynchronously, but the order in which the modules are executed is strictly in accordance with the order in which the modules appear in the code (require), which is more logical. What do you say, Requirejs?

And Requirejs will execute the (dependent) module as soon as possible, equivalent to all the require are advanced, and the order of the module execution is not necessarily 100% is first mod1 again MOD2
So you see that the order of execution is completely different from what you expected! Shake It ~ requirejs!

Because he thinks his test code

Define(function(Require,Exports,Module){Console.Log(' Require Module:main ');VarMod1= require ( "/mod1 ' mod1. Hello (); var mod2 = require ( mod2. Hello (); return {hello: function () {console. Log ( ' hello Main ' } };                

The result of the operation should be sequential (the result under Sea.js):

require module: mainrequire module: mod1hello mod1require module: mod2hello mod2helo main

And should not be asynchronous under the Require.js:

require module: mod2require module: mod1require module: mainhello mod1hello mod2helo main

The question, however, is why "the order in which modules are executed" should be "strictly in the order that modules appear in code (require)"? And "Is this more logical?"

If he seajs the results of the operation to demand Requirejs, that Requirejs must suffer. AMD standards never specify the order in which modules are loaded, it just needs to be guaranteed:

the dependencies must is resolved prior to the execution of the module factory function, and the resolved values Sho Uld be passed as arguments to the factory function with argument positions corresponding to indexes in the dependencies AR Ray.

Comments below someone (Jockchou) 's reply is more pertinent:

I personally feel requirejs more scientific, all dependent modules to be executed first. If the A module relies on B. When the execution of a dosomething () in a, then to rely on the execution of B module require (' B '), if the B module error, how to rollback dosomething operation?
Import, include, and useing in many languages are first performed by the imported classes or modules. What is the point of executing the current module if the module being imported has a problem with an error?

landlord said Requirejs is a pit, because you do not understand the AMD "asynchronous module" definition, the dependent module must precede the current module execution, and no dependency of the module, can not be successively.

Imagine Factory is a module factory, and rely on dependencies is the raw material of the factory, in the factory production, is the first raw materials in its own factory processing, or the raw materials of the factory to move to the current factory when needed, When to process, which overall time is more efficient? It is obvious that Requirejs,requirejs is loaded and ready to use. In response to a user's operation, the current factory is in production, when the need for some kind of raw materials, suddenly to stop production, to start raw material processing, this is not to make the current factory very dry?

It seems that there is not much difference between the two.


But consider such a business situation, consider a certain function only to the login user open, so that requirejs in advance to load the module is necessary? (because users who come to your page will not log on when they leave).

This is a very practical problem, a page can have a lot of features, such as landing, sharing, message, collection ... But not necessarily every user to the page will use these features, if all as the dependency of the page module loading, the page must be a very small burden.

But Seajs can be loaded, like code can write

define(function () { if (user_login) { require(login_feature_module) } document.body.onclick = function () { require(show_module) }})

I agree with this statement:

import, include, and useing in many languages are first performed by the imported classes or modules. What is the point of executing the current module if the module being imported has a problem with an error?

But personally feel that considering the performance of the page, you may want to consider the lazy loading of the module to be imported (lazy load).

Would you think what I said above lazy loading is a fantasy?

But no, you go and look at the Renren profile now.

The "related to Me", "photo album", and "share" are all clicked before the corresponding module is loaded.

Facebook is even more serious, considering not only the functional modules of the different teams in the interior, but also the third-party function modules.

As early as 09, they used a static resource management scheme (static Resource Management) to manage the js/css static files required for a feature:

In a nutshell, it is the HTML fragment that is required by the page to decide whether to load and package the functions required by the JS and style. This means that the static file needs to be available after the HTML "declaration".

For details, refer to this: Frontend performance Engineering in Facebook:velocity 2009

# # Execution Variance

To enhance the contrast, when we define a dependent module, we deliberately let its factory function take a considerable amount of time, such as 1 seconds:
Dep_a.js defined as follows, Dep_b/dep_c defines the sameDefine(function(Require,Exports,Module){(function(Second){VarStart=+NewDate();While(Start+Second*1000>+NewDate()){}})(Window.Exe_time);Window. Exe_time = 1; the 1s is executed continuously hereExports.Foo=function(){Console.Log(A);}})Load three identical modules simultaneously in mainRequire.js:Require(["Dep_a","Dep_b","Dep_c"],function(A,B,C){}); //sea.js:define (function Span class= "NX" >requireexportsmodule) {var mod_a =  Require (var mod_b = require (  "dep_b" ); var mod_c = require (  "Dep_c" );                

Requirejs-loaded waterfall diagram:

Seajs-loaded waterfall diagram:

If you split the execution of a module into execution define and perform factory functions (both for Requirejs and SEAJS), you can see:

    • Requirejs: The factory function execution of a module is immediately followed by the define (that is, the Evaluate script module file)
    • SEAJS: The factory function that executes a module needs to wait for all modules to define complete.

The point is not these, I want to say that I see a shining spot in the SEAJS.

In the above section I mentioned the lazy loading module, which requires 1 when loading the module. Temporary request module file; 2. Execute the factory function.

But if we load the page just to execute the define of the lazy-loaded module (from the above two graphs we can see that the cost of define is very small), and try not to execute the factory function.

So when you really need lazy loading, just execute the factory function. Does this not allow the module to respond more timely and more reliable?

This can be achieved. But the technical details will not be mentioned. This can be used as a scheme for optimizing module loading.

So take a look at the postscript to the quoted article.

Note what I'm talking about here is executing (actually running the code in the Define) module, not the load (load file) module.
Module loading is parallel, no difference, the difference lies in the timing of the implementation of the module, or is resolved.

To illustrate the problem of blocking, Cui Hua

Lazy Execution of Seajs

Pre-execution of Requirejs

Note the huge pinyin-dict.js module, taken from pinyin.js, copied n times to increase its "weight", enhance the presentation effect, if you are interested, you can try it yourself.

It is clear that Requirejs's approach is to load all dependent modules in parallel, and after parsing, then start executing other code, so the execution results will only "pause" 1 times, and complete the process will be faster than SEAJS.

While Seajs is the same as loading all dependent modules in parallel, but does not immediately execute the module, wait until the real need (require) to start parsing, where time is spent, because the module in this special case is huge, resulting in a "pause" 2 times, this is what I call "lazy execution" in the Seajs.

Finally thank you for all the suggestions, I do not say here Seajs and Requirejs which better, just to illustrate the difference between them, all kinds of trade-offs please according to the actual situation to set, hope to help everyone.

See here, it is estimated that the situation is not the same, the last is the choice of people.

Record: Sea.js and Require.js configuration vs. performance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.