The concept of the module loader may be slightly exposed to the front-end development of children's shoes are not unfamiliar, through the module loader can effectively solve these problems:
- JS file dependencies.
- Optimization of blocking problems caused by script tags by asynchronous loading
- It can be easily modularized and reused in a file-based format.
Mainstream JS module loader has requirejs,seajs, and so on, the loader may be due to follow the specifications of different there are subtle differences, from a purely user point of view, the reason for choosing Requirejs instead of Seajs mainly because:
- There are almost no significant performance differences or major problems in the implementation of the function.
- Document richness, Requirejs far better than SEAJS, take the simplest to load jquery and jquery plug-in this matter, although the two implementations of the same way, but requirejs there can be directly to use the DEMO,SEAJS also to read the document himself slowly toss. The solution to some problems, Requirejs is also easier to find the answer to the keyword.
Requirejs load jquery + jquery Plugin
Perhaps for the general web App, the probability of the introduction of jquery and related plug-ins is the largest, Requirejs also kindly give the corresponding solution and dynamic loading jquery and plug-in documents and instance code.
In the latest jquery1.9.x, jquery has finally registered itself as an AMD module, which means that it can be loaded directly by Requirejs as a module. There are two ways to load an older version of jquery:
1. Let jquery load before Requirejs
2. Take a little bit of jquery code and wrap it in the jquery code:
define (["jquery"], function ($) { //$ is guaranteed to being jquery now */
In the Requirejs example, the Requirejs and jquery are merged directly into a single file, which is recommended if jquery is used as the core repository.
There are also two ways to do this for jquery plugins
1. Wrapping code outside the plugin
define (["jquery"], function ($) { //Put here the plugin code. });
2. Register the plugin before loading with REUQIREJS code (for example, in Main.js)
Requirejs.config ({" shim": { "Jquery-cookie" : ["jquery"] } });
Requirejs loading a third-party class library
Third-party libraries outside of jquery are also used in the instance app, and if the class library is not a standard AMD module and does not want to change the code for these class libraries, it needs to be defined in advance:
Require.config ({ paths: { ' underscore ': ' Vendor/underscore ' }, shim: { underscore: { Exports: ' _ '}} );
modular processing of CSS files
In Requirejs, the concept of the module is limited to JS files, if you need to load images, JSON and other non-JS files, Requirejs implemented a series of loading plug-ins.
But unfortunately, the Requirejs official does not have the CSS module processing, but we in the actual project can often encounter some scenes, such as a carousel of picture display bar, such as the Advanced editor and so on. Almost all of the rich UI components are composed of JS and CSS, and there is a concept of module and dependencies between CSS.
In order to better integrate with Requirejs, the REQUIRE-CSS is used here to solve the problem of modularization and dependency of CSS.
REQUIRE-CSS is a Requirejs plug-in, the download will css.js and normalize.js placed in the Main.js peer can be loaded by default, such as in our project need to load jquery mobile CSS file, Then you can call this directly:
Require ([' jquery ', ' CSS!.. /css/jquery.mobile-1.3.0.min.css '], function ($) { });
However, since this CSS is essentially part of the jquery mobile module, it is better to place the definition of this CSS file in the jquery mobile dependency, and ultimately our Requirejs definition is:
Require.config ({ paths: { ' jquerymobile ': ' vendor/jquery.mobile-1.3.0 ', ' jstorage ': ' Vendor/jstorage ' , ' underscore ': ' Vendor/underscore ' }, shim: { jquerymobile: { deps: [ ' CSS!.. /css/jquery.mobile-1.3.0.min.css ' ] }, underscore: { exports: ' _ '}} });
when using a module, you only need to:
Require ([' jquery ', ' underscore ', ' jquerymobile ', ' jstorage '], function ($, _) { });
JQuery Mobile CSS files will be automatically loaded, so that CSS and JS are integrated into a module. Similarly, other modules with complex dependencies can do similar processing, and REQUIREJS will solve the logic of dependency.
Loading and waiting for a data source
Web apps typically load back-end data dynamically, and the data format can typically be JSON, JSONP, or directly a JS variable. Here is an example of a JS variable:
var restaurants = [ { "name": "KFC" }, { "name": "7-11" }, { "name": "Chengdu Snack" } ]
Load this piece of data:
$.getscript (' Data/restaurants.json ', function (e) { var data = window.restaurants; alert (data[0].name); KFC });
A single source of data is really simple, but often there are multiple data sources in an application, such as the UI in this instance app that needs to load user information, restaurant information, ordering information, three kinds of data to work. If you just rely on multiple layers of nested callback functions, you might have a very heavy coupling of code.
To solve the problem of multiple data loading, my usual solution is to construct a Dataready event response mechanism.
var Foodorder = {//the function to be executed after data load is temporarily present here Datareadyfunc: []//Data source URL and loading status, DataSource: [{ URL: ' Data/restaurants.json ', Ready:false, data:null}, {url: ' Data/users.json ', Ready:false, Data:nul L}, {url: ' Data/foods.json ', Ready:false, data:null}]//Check that the data source is all loaded, isready:funct Ion () {var isReady = true; for (var key in This.datasource) {if (This.datasource[key].ready!== true) {IsReady = false; }} return isReady; }//Data source is fully loaded, run the function stored in Datareadyfunc, Callready:function () {if (true = = = This.isready ()) { for (var key in This.datareadyfunc) {This.datareadyfunc[key] (); }}}//For external invocation, the externally entered function is temporarily present in Datareadyfunc, Dataready:function (func) {if (typeof func !== ' function ') {return false; } thiS.datareadyfunc.push (func); }, Init:function () {var = this; var _initelement = function (key, URL) {$.getscript (URL, function (e) {////data is stored in Datasou after each load) RCE, set the ready state to True and call callready Self.datasource[key].data = Window[key]; Self.datasource[key].ready = true; Self.callready (); }); } for (Var key in This.datasource) {_initelement (key, This.datasource[key].url); } } }
to use:
Foodorder.dataready (function () { alert (1); });
The alert within the Dataready will be executed after all data has been loaded.
The logic of this process is not complex, and all the methods to be executed are staged through Dataready, waiting for the data to be fully loaded and then executed, and this method is still common for more complex scenarios.
JavaScript modularity: Load on Demand with Requirejs