Summary of Requirejs Learning notes

Source: Internet
Author: User
Tags function definition script tag


A Why do you use Requirejs?

With the development of the project, JS files more and more large, need to be divided into JS files.


<script src= "A.js" ></script>

<script src= "B.js" ></script>

<script src= "C.js" ></script>

First of all, the above way when the Web page load, the browser will stop the rendering of the page, the more loading files, the Web page will lose the response time longer;

Secondly, because of the dependence of JS files, we must strictly ensure the loading sequence, the most dependent module must be put to the final load.

Requirejs solved the above two problems very well.

1. Implement the asynchronous loading of JS files to avoid web page loss of response.

2. Manage the dependencies between the modules, easy to write and maintain the code.

Two What is Requirejs

1. Requirejs is a JavaScript file and module framework that can be downloaded from http://require.org, which supports browsers and server environments like Node.js. Using Requirejs, you can sequentially read dependent dependency modules.

<script src= ' js/require.js ' defer async=true></script>

The Async property indicates that the file needs to be loaded asynchronously to prevent the Web page from losing its response. Defer is only compatible with IE, so write the defer.

2. <script src= "script/require.js" data-main= "Scripts/main" ></script>

Data-main Property: Specifies the main module of the Web page program, and when Requirejs is loaded, he uses the Data-main property to search for a script file that is main.js. This file will be first loaded by the Require.js file.

Data-main need to set a root path for all the script files. Depending on the root path, REQUIREJS will load all the associated modules. Because the require.js default file suffix is js, you can abbreviate main.js to main.

What Requirejs do is load these dependencies through the Head.appendchild () function when using the script tag to load your defined dependencies. After dependency loading, Requirejs calculates the order of the module definitions and calls in the correct order. This means that you simply define a ' root ' to read the dependencies you need, and in order to use these dependencies correctly, the Require.js loaded modules need to use the Requirejs API, which means that the module must use a specific define () function to write the module.


The Requirejs API, which exists under the namespaces created in Requirejs load-Requirejs, is the application of the AMD specification. AMD is a definition of a module, so that the module and its dependencies can be loaded asynchronously, but in the correct order. The API is basically the following three functions:

Define: This function is primarily used to create modules.

Require: This function is used for read dependencies.

Config: This function is used to configure Requirejs

If a module does not rely on other modules, it can be directly defined in its define () function:

If you now have a math.js file that defines the math module, then the definition math.js is as follows:

Math.js

Define (function () {

var add=function (a,b) {

return a+b;

};

})

Load Math.js Module

Require ([' Math '],function (math) {

Alert (Math.add (1,2));

});

If math also relies on other modules, the first argument to the Define () function must be an array indicating that the module also relies on other modules.

When the require () function loads the math module, the math-dependent module is loaded first.

3. After loading the require.js, take a look at how to configure the module main.js need to load through the Require.config function.

The config parameter is an object. This optional parameter object includes a number of configuration parameter options. Here are some of the configurations you can use:

baseurl--is used to load the module root path.

paths--is used to map a module path that does not exist under the root path.

The shims--configuration module does not use the Requirejs function definition, but you still want to use it through Requirejs. Then you need to define it as a shim in the configuration.

exports--the variable name of the output, representing the name of the outside call for this module

deps--loads a dependency array.

Require.config ({

BaseURL: ' application/views/frontend/build/'

, paths:{//paths is used to map a module path that does not exist under the root path

Text: ' Lib/require/text '

, jquery: ' Lib/jquery-1.9.0.min '

}

, shim:{//is specifically used to configure incompatible modules

' jquery ': {

Exports: ' jquery '//exports the variable name of the output, representing the name of the module outside the call

}

, ' Jquery_icheck ': {

Deps: [' jquery ']//deps array, indicating that the module relies on the above jquery module.

, exports: ' Jquery_icheck '

}

}

});


Three Require.js Plug-ins

The Domready plug-in allows the callback function to run after the page DOM structure has completed loading.

The text and image plug-ins allow require.js to load texts and pictures:

Define ([

' Text!otxt.txt ',

' Image!oimg.jpg '

],function () {

Document.body.appendChild (OIMG);

document.write (Otxt);

});

Four. A simple example of the project directory is as follows:

-index.html

-scripts folder

–controller folder

-miancontroller.js

-controller1.js

-controller2.js

–directives folder

-maindirective.js

-directive.js

–app.js

–router.js

–main.js

Back to Top
Second, home

First of all, your index.html is probably as follows

<!doctype html>
<!--<meta charset= "Utf-8" >
<meta http-equiv= "x-ua-compatible" content= "Ie=edge, chrome=1" >
<body>
<!--other HTML content-->
<script type= ' text/javascript ' src= '. /scripts/lib/require.js ' data-main= '. /scripts/main.js ' ></script>
</body>
On the homepage index.html only need to introduce the Requirejs library file, and indicates the entry function Main.js, uses the manual to start the ANGULARJS application, therefore does not need the homepage to add ng-app= ' webApp '.

Back to the top of

Third, the configuration mian.js


Require.config ({
paths:{
Some library files
' jquery ': '//cdn.staticfile.org/jquery/1.10.2/jquery.min ',
' Angular ': '//cdn.staticfile.org/angular.js/1.2.10/angular.min ',
' Angular-route ': '//cdn.staticfile.org/angular-ui-router/0.2.8/angular-ui-router.min ', ' domReady ': '// Cdn.staticfile.org/require-domready/2.0.1/domready.min ',
JS file
' Bootstrap ': ". /scripts/bootstrap ",
' App ': '. /scripts/app ",
' Router ': ". /scripts/router "
..... and other JS files, here omitted
},
shim:{
' Angular ': {
Exports: ' Angular '
},
' Angular-route ': {
deps:[' angular '],
Exports: ' Angular-route '
}
},
deps:[' Bootstrap '],
Urlargs: "bust=" + (new Date ()). GetTime ()//prevent read cache, adjust trial
});
About Require.config () in the configuration is as follows (according to their own project situation, here I simply configured),

So the whole thing about main.js this file is that all files are loaded asynchronously by Requirejs

Notice the deps:[' Bootstrap ', which is to tell us to load the Bootstrap.js file first.

Back to Top

Four, manual start Angularjs application

And bootstrap.js is what I use to manually start the ANGULARJS application, the following code


define ([' Require ',
' Angular ',
' Angular-route ',
' jquery ',
' App ',
' Router '
],function (require,angular) {
' Use strict ';
Require ([' domready! '],function (document) {
Angular.bootstrap (document,[' WebApp '));
});
});
Here depends on App.js and router.js, let's see what these two files do separately

Back to Top

V. Web site routing Settings

We use ui-router here. So our router.js should be like this, mainly used to define the routing, about ui-router configuration please check the relevant knowledge, here is simply skip


Define (["App"],
Function (APP) {
Return App.run ([
' $rootScope ',
' $state ',
' $stateParams ',
function ($rootScope, $state, $stateParams) {
$rootScope. $state = $state;
$rootScope. $stateParams = $stateParams
}
])
. config (function ($stateProvider, $urlRouterProvider, $locationProvider, $uiViewScrollProvider) {
Jump to top when changing state
$uiViewScrollProvider. Useanchorscroll ();
Default entry First redirect
$urlRouterProvider. Otherwise ('/home ');
$stateProvider
. State (' home ', {
Abstract:true,
URL: '/home ',
Views: {
' main@ ': {
Templateurl: '.. /view/home.html '
}
}
})
})

Back to Top
VI. angular.module

Let's take a look at the usual we write ANGULARJS application is this

var app = angular.module ("xxx", ["xxx"]);
App.controller ("foo", function ($scope) {});
App.directive (...)

So our app.js is supposed to be like this.

define (["Angular",
' Maincontroller ',
' Maindirective '
],function (angular) {
Return Angular.module ("WebApp", [' ui.router ', ' ngstorage ', ' ngsanitize ', ' webapp.controllers ', ' webapp.directive ']);
})
The Maincontroller and maindirective that we rely on in our app.js are mainly used to load angular controllers and instructions.

Back to Top
Seven, Controller

This is our maincontroller.js.

define ([' Controller1 ', ' Controller2 '],function () {});
Mainly used to load the various controllers (all controllers will be loaded in this file), otherwise do not have to do other, because we can have a lot of controller files, according to the specific needs to add.

Controller1.js files (similar to other controller controller2 files)


define (['.. /scripts/controller/module.js ', ' jquery '],function (controllers,$) {
' Use strict ';
Controllers.controller (' Controller1 ', function ($scope) {
The specific JS code of the Controller
})
})

Which relies on module.js

And Module.js is as follows

define ([' angular '], function (angular) {
' Use strict ';
Return Angular.module (' webapp.controllers ', []);
});

Viii. directives

Similarly miandirective.js is similar. Reference Controller

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: info-contact@alibabacloud.com 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.