Use methods based on Require. js (Summary) and require. js

Source: Internet
Author: User

Use methods based on Require. js (Summary) and require. js

I. Why do I need to use require. js?

First, if a page is loaded with multiple js files, the browser stops web page rendering. The more files are loaded, the longer the webpage will lose response time. Second, because JavaScript files are dependent on each other, the loading sequence must be strictly guaranteed. When the dependency is complex, coding and maintenance become difficult.

Require. js is used to solve these two problems:

1. asynchronous loading of js files to prevent webpage response loss;
2. Manage dependencies between modules to facilitate code compilation and maintenance.

Ii. Loading of require. js

Step 1: download the latest version from the official website and load it on the page.

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

Loading this file may cause the webpage to lose response. You can load it at the bottom of the page or write it like this.

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

The async attribute indicates that the file needs to be asynchronously loaded to avoid webpage response loss. IE does not support this attribute and only supports defer. Therefore, defer is also supported.

After loading require. js, the next step is to load our own code, that is, the entry, which can be called the main module. If the file name is called main. js, write it as follows:

<Script src = "js/require. js" data-main = "js/main"> </script>. js suffixes can be omitted.

Iii. Writing of the main module

If the main module depends on jQuery, you can write

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

Iv. require. config () method

require.config({   paths: {     "jquery": "jquery.min",     "underscore": "underscore.min",     "backbone": "backbone.min"  } }); 

The above Code provides the file names of the three modules. The path is in the same directory (js subdirectory) as main. js by default ). If these modules are in other directories, such as the js/lib directory, there are two writing methods.

• Specify paths one by one

require.config({   paths: {     "jquery": "lib/jquery.min",     "underscore": "lib/underscore.min",     "backbone": "lib/backbone.min"  } }); 

• Another method is to directly change the base Directory (baseUrl ).

require.config({   baseUrl: "js/lib",   paths: {     "jquery": "jquery.min",     "underscor: "underscore.min",     "backbone": "backbone.min"   } }); 

• If a module is on another host, you can directly specify its url, for example

require.config({   paths: {     "jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min"  } }); 

V. AMD module writing

The modules loaded by require. js adopt AMD specifications. That is to say, the module must be written according to AMD regulations.

Specifically, the module must be defined using a specific define () function. If a module does not depend on other modules, it can be directly defined in the define () function.

// math.js define(function (){   var add = function (x,y){     return x+y;   };   return {     add: add   }; }); 

The loading method is as follows:

 // main.js require(['math'], function (math){   alert(math.add(1,1)); }); 

If this module depends on other modules, the first parameter of the define () function must be an array that specifies the dependency of this module.

Define (['mylib '], function (myLib) {function foo () {myLib. doSomething () ;}return {// function foo: foo };} in the return module };});

When the require () function loads the above module, it loads the myLib. js file first.

6. Load nonstandard modules (shim usage)

// app.js  function sayHello(name){   alert('Hi '+name); } 
// Main. js require. config ({shim: {'app': {// name of the target file to be loaded. Exports: 'sayhello' // The value of exports is my. name of the external interface provided by js }}); require (['app'], function (sayHello) {alert (sayHello ())})

Exporting a function means that we get a javaScript class

But if I write a lot of functions in my. js, it is a little troublesome to integrate them into a function. Do I want to export them directly? The method is as follows:

// app.js function sayHi(name){  alert('Hi '+name); } function sayHello(name){  alert('Hiello '+name); }
// Main. js require. config ({shim: {app: {init: function () {// here use init to return the return {sayHi: sayHi, sayHello: sayHello }}}); require (['app'], function (a) {. sayHi ('hangsan ');. sayHello ('lisi ');});

Ordered shim Import

Require. config ({shim: {'jquery. ui. core': ['jquery '], // indicates that 'jquery is imported after jquery is imported. ui. widget ': ['jquery'], 'jquery. ui. mouse ': ['jquery'], 'jquery. ui. slider ': ['jquery']}, paths: {jquery: 'jquery-2.1.1/jquery ', domReady: 'require-2.1.11/domready', 'jquery. ui. core': 'jquery-ui-1.10.4/development-bundle/ui/jquery. ui. core', 'jquery. ui. widget ': 'jquery-ui-1.10.4/development-bundle/ui/jquery. ui. widget ', 'jquery. ui. mouse ': 'jquery-ui-1.10.4/development-bundle/ui/jquery. ui. mouse ', 'jquery. ui. slider ': 'jquery-ui-1.10.4/development-bundle/ui/jquery. ui. slider '}); require (['jquery', 'domainready', 'jquery. ui. core', 'jquery. ui. widget ', 'jquery. ui. mouse ', 'jquery. ui. slider '], function ($) {$ ("# slider "). slider ({value: 0, min: 0, max: 4, step: 1, slide: function (event, ui ){}});});

The above post is based on the use of Require. js (Summary), which is all the content shared by Alibaba Cloud xiaobian. I hope to give you a reference and support for the customer's house.

Related Article

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.