Requirejs Introduction and a complete example

Source: Internet
Author: User
Tags script tag

What is Requirejs?

Requirejs is a javascript written by the JS framework, the main function is to be based on different dependencies on JavaScript and other files to load work, can be easily understood as JS file loader, it is very suitable for use in the browser, It can ensure that the dependent JS file loading is completed before loading the current JS file, which in a large number of JS files in the project to ensure that each JS file loading sequence, It is useful to avoid the problem that a function or a variable cannot be found when a file is loaded slowly for some reason, and other fast-loading files need to rely on some of its features, which is also the main value of Requirejs.

Quick and simple to understand the essentials:

1, require will define three variables: define, require, Requirejs, require = = = Requirejs , generally use require shorter, page loading without blocking rendering;
2, define(function () {...}); From the name you can see that the API is used to define a module;
3, require([' Amodule ', ' Bmodule '],function (A, b) {...}) load the dependent module and execute the post-load callback function;
4, when using Requirejs, load the module without writing. js suffix , of course, can not write suffixes;
5, require.config({...}) is used to configure the module load location and set the basic path, etc.;
6. The script tag for loading Requirejs scripts adds the data-main attribute, This property specifies that after loading the reuqire.js, it is loaded with Requirejs to load the value of the JS file under the path and run, so generally the JS file is called the main JS file, similar to the function of the main function in C or Java language, and then the Require.config configuration plus the master file can make each Page Use this configuration, and then the page can be directly used require to load all the short module name, so that in one place to configure all places to use, and the use and management of the module alias is also more convenient. Example: < script data-main= "Js/main" src= "js/require.js" ></script>
7, when the script tag specifies the Data-main attribute, require will default to data-main the specified JS as the root path;
8, require loaded modules are generally required to comply with the AMD specification, that is, the use of define to declare the module;
9, loading non-AMD specification JS, this time need to use another function: shim; for example:
require.config ({    paths:{        "underscore":"/http/ Www.xxx.com/xpath/xFile.js"    }    , shim: {        "underscore " : {            "_";        }    }});

Well, here's a brief introduction, here's a practical example:

The design requirement for this example is that the Workjs01.js file relies on jquery, Workjs02.js relies on workjs01.js, only when the dependent files are loaded, and finally the message is typed on the page,

First look at the example file directory structure:

-------------------------------------------------userExample01    |----*.html//html page    |----Scripts        |       | ----*.js//main.js, require.js etc            |----lib   //each Third party Framework            |     | ----jquery            |            | ----*.js            |----  work//Various business jobs JS file                   |----*.js//-------------------------------------------------

1. HTML file index.html Note One of the Requirejs loading methods, see the Script tab

<! DOCTYPE HTML Public"-//W3C//DTD XHTML 1.0 transitional//en"   "HTTP://WWW.W3.ORG/TR/XHTML1/DTD/XHTML1-TRANSITIONAL.DTD"> "http://www.w3.org/1999/xhtml"> "Content-type"Content="text/html; Charset=utf-8"/> <title>requireJS</title> <style type="Text/css"> *{font-family:"Microsoft Ya-Black","Microsoft Yahei", Verdana;} . Text01{line-height:20px;font-size:13px;font-Family:verdana;} pre{margin:0px;padding:2px 0px;font-size:13px;font-Family:verdana;} . div01{border:1px Solid Red;text-align:left;padding:5px; }  </style>  on"Loadmsgcon" class="DIV01"></div> <script data-main= "Scripts/main" src= "Scripts/require_v2.1.11.js" ></script>
<!--Note that the Requirejs file corresponds, while the Data-main property value is written to
</body>

2, the main file main.js generally use this to carry out the main file, each file according to a certain number of files to complete the loading of each file; Recommended note notes and writing format, to facilitate the formation of good habits and code norms;

//1. About Require.js config//configuration Information; Require.config ({//define all JS file path base on the This base path//actually this can setting same to data-main attribute in script tag//define the basic path of all JS files, which can actually have the same root path as the data-main of the script tag.BASEURL:"./scripts"         //define each JS frame path, not need to add. js suffix name//define each JS frame path name without adding a suffix. js, paths:{"jquery":["Http://libs.baidu.com/jquery/2.0.3/jquery","Lib/jquery/jquery-1.9.1.min"]//write the corresponding jquery right here.,"workjs01":"work/workjs01"           ,"WORKJS02":"WORK/WORKJS02"          ,"Underscore":"" //path not provided, can be searched online and then added    }            //include not AMD specification JS frame code//JS Framework with other non-AMD specifications, shim:{"Underscore":{              "exports":"_"          }      }        }); //2,about Load Each JS code basing on different dependency//loading each JS file according to different succession dependenciesRequire (["jquery","workjs01"],function ($,W1) {require (['WORKJS02']);  }); 

3, one of the business documents, Workjs01.js pay attention to the syntax to see how the module is written, it is recommended to note the various notes and writing format, easy to develop good habits and code specifications

Define (['jquery'],function ($) {//note the notation of the module//1,define intenal Variable area//Variable definition Area    varMyModule = {};//Recommended Way    varModuleName ="Work Module"; varVersion ="1.0.0"; //2,define intenal Funciton Area//function Definition Area    varLoadtip =function (tipmsg, Refconid) {vartipmsg = Tipmsg | |"module is loaded finish."; if(undefined = = = Refconid | |NULL= = = Refconid | |""= = = Refconid+"") {alert (tipmsg); }Else{              $('#'+ (refconid+"") . HTML (tipmsg);            }      }; //3,should is return/output a OBJECT[EXPORTS/API] If other module need//If you need to expose (return) This module API (related defined variables and functions) to other external modules to useMymodule.modulename =ModuleName; Mymodule.version=version; Mymodule.loadtip=Loadtip; returnMyModule; /*//this is same to four lines code upper//return {"ModuleName": "Work Module", "Vers", as in line four above     Ion ":" 1.0.0 ", loadtip:loadtip}; */     }); 

4, one of the business documents, Workjs02.js recommended note Document notes and writing format, easy to develop good habits and code norms;

Define (['workjs01'],function (w01) {//1,define intenal Variable area//Variable definition Area    varModuleName ="Work Module"; varModuleversion ="1.0.0"; //2,define intenal Funciton Area//function Definition Area    varsethtml =function (refid,strhtml) {if(undefined = = = Refconid | |NULL= = = Refconid | |""= = = Refconid+""){              return; }Else{              $('#'+ (RefId +""). HTML (strhtml+"");            }      }; //3,auto Run when JS file is loaded finish//After js loading, you can run a function at the end of the module [return], that is, to complete the automatic operationW01.loadtip ("This page files are loaded complete, this page design Workjs01.js file relies on jquery, Workjs02.js relies on workjs01.js","Loadmsgcon"); //4,should be return/output a object[exports/api]//If you need to expose (return) This module API (related defined variables and functions) to other external modules to use    return {          "ModuleName": ModuleName,"version": Moduleversion}}); 

Note: the corresponding Requirejs and jquery are not given here, to the corresponding online or official website download to the corresponding directory, note that the change in the file name corresponding to, see the corresponding local notes;

  

This example is simple, but basically contains most of the actual Requirejs knowledge points , the annotations are very clear, at the same time note the organization structure of the file, the definition of Requirejs configuration, call relations, the module's writing, the module's internal wording, the loading and invocation of dependent files, And how the module automatically runs a function, and so on.

Requirejs Introduction and a complete example

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.