Example tutorials for loading JavaScript modules using the REQUIREJS Library _javascript class Library

Source: Internet
Author: User
Tags define definition script tag

JS through the script label default load is synchronized, that is, the first script inside the completion of the JS loading, and then began to load the second, and so on, until all JS files loaded complete. And JS dependency must be in the order of the script to ensure that, and in the JS load, the browser will stop responding, which greatly affected the user experience, based on this, a lot of the solution JS and loaded The program appears, require JS is one of them.

Requirejs loaded modules, generally in line with the AMD standard module, that is, with the define definition, with Ruturn return exposure method, variable module; Requirejs can also load fly AMD standard module, but more troublesome, this time does not involve.

Require loading JS main covers the following aspects:

    • The script tag Data-main property declares Requirejs loaded entry module, async= "true" (non IE) and defer (IE) tags indicate asynchronous loading.
    • Require.config Configuration Module corresponding path
    • Require declaration dependencies

HTML Demo

<script src = "js/require.js" defer async= "true" data-main= "Js/main" >

<!--gives the Requirejs path, declares as asynchronous loading, and specifies that the entry module is

main.js (can omit. js)-->

Main.js

 Require.config ({
   ///declaration of the location of the module
   paths: {
     "jquery": "Libs/jquery"
     "Login": "Libs/login"
   }
   // Or use BaseURL to specify the path of all modules
   BaseURL: "Js/libs"
 });
 Loading a module with require, the first parameter is an array, the module to be loaded, is loaded in array order, and the second is the callback function, which is executed after all loads have completed.
 require ([' jquery ', ' Login '],function ($,login) {
   alert ("jquery and Login module load success!");
   Login.do_login ();
   Some else
 });

Compliant with AMD's login module definition

 Relies on the definition of jquery
 define ([' jquery '],function ($) {
   //some definations
  function Do_login () {
    $.post ( '/sessions/create ', {uname:$ ("#uname"). Val (),
         password:$ ("#password"). Val ()},function (data) {
     //some 
   });
   return {do_login:do_login};}} 
 );

Does not rely on the definition of other modules
define (function () {
 //some definations return
 {xx:xx};
});

Rails does not apply the JS loader, on the one hand is the new version of the rails asset pipe will be all JS files packaged into a JS file, no more than JS loading state, on the other hand turbolink use of a mixed so-called Pjax technology, the default link to Ajax way , only get the BOD part of the HTML, the head part does not change, so that JS loading only the first time when the site is opened.


Case One: loading JavaScript files

 <script src= "./js/require.js" ></script> 
   <script> 
  require (["./js/a.js", "./js/b.js"], function () { 
       Myfunctiona (); 
       Myfunctionb (); 
    }); 
   </script>

This string array parameter in the Require method can allow different values, when the string is terminated with ". js", or starts with "/", or is a URL, the Requirejs thinks the user is loading a JavaScript file directly, otherwise, when the string is similar to " My/module ", it will consider this a module and will load the JavaScript file of the corresponding module with the user-configured BaseURL and Paths. The configuration section will be covered in more detail later.

The point here is that Requirejs by default does not guarantee that Myfunctiona and MYFUNCTIONB must be executed after the page is loaded, and that when there is a need to ensure that the page is loaded after the script is executed, REQUIREJS provides an independent Domready module, you need to go to the Requirejs official website to download this module, it is not included in the Requirejs. With the Domready module, case one of the code to do a little modification coupled with the dependence on the Domready can be.

Case two: After the page loads execute JavaScript

 <script src= "./js/require.js" ></script> 
   <script> 
  require (["domready!", "./js/a.js", ". Js/b.js "], function () { 
       Myfunctiona (); 
       Myfunctionb (); 
    }); 
   </script>

After executing the code for case two, you can see through Firebug that Requirejs will insert a.js and b.js on the current page and declare a < script> label separately for downloading JavaScript files asynchronously. The async attribute is currently supported by most browsers, indicating that the JS file in the < script> tab will not block downloads of other page content.

Case three: Requirejs inserted < script>

 <script type= "Text/javascript" charset= "Utf-8" "async=" _ " 
 data-requirecontext=" data-requiremodule= A.js "src=" Js/a.js "></script>

Use Requirejs to define JavaScript modules

The JavaScript module here is different from the traditional JavaScript code in that it does not need to access global variables. The modular design allows JavaScript code to access the "global variables", through dependencies, these "global variables" as parameters to pass to the module's implementation body, in the implementation of the access or declaration of global variables or functions, Effectively avoids large and complex namespace management.

As described in the COMMONJS AMD specification, the definition of JavaScript modules is implemented through define methods.

Let's take a look at a simple example by defining a student module and a class module, implementing creating student objects in the main program and putting student objects into class.

Case FOUR: Student module, student.js

 Define (function () {return 
   { 
    createstudent:function (name, gender) {return { 
         name:name, 
         Gender: gender};}; 
 

Case five: class module, Class.js

Define (function () { 
 var allstudents = []; 
    return { 
      ClassID: "001", 
      Department: "Computer", 
      addtoclass:function (student) { 
      Allstudents.push ( Student); 
      }, 
      getclasssize:function () {return 
      allstudents.length; 
      } 
   ;} 
 );

Case SIX: Main program

 Require (["Js/student", "js/class"], function (student, CLZ) { 
 Clz.addtoclass (student.createstudent ("Jack", " Male ")); 
 Clz.addtoclass (Student.createstudent ("Rose", "female")); 
 Console.log (Clz.getclasssize ()); Output 2 
 });

Student modules and class modules are separate modules, we define a new module, which relies on student and class modules so that the logic of the main program part can be packaged.

Case Seven: The manager module that relies on the student and class modules, manager.js

Define (["Js/student", "js/class"], function (student, CLZ) {return 
 { 
  addnewstudent:function (name, gender) { 
  Clz.addtoclass (student.createstudent (name, gender)); 
    }, 
  getmyclasssize:function () { 
  return Clz.getclasssize ();}}; 
 

Case EIGHT: the new main program

 Require (["Js/manager"], function (manager) { 
 manager.addnewstudent ("Jack", "male"); 
 Manager.addnewstudent ("Rose", "female"); 
 Console.log (Manager.getmyclasssize ());//Output 2 
 });

With the code example above, we have a clear understanding of how to write a module, how this module is used, and how dependencies between modules are defined. There are some tips to use:

Try not to provide the ID of the module, as described in the AMD specification, this ID is optional and, if provided, will affect the mobility of the module in the Requirejs implementation, and file location changes will result in the need to manually modify the ID.

Each JavaScript file defines only one module, and the search algorithm for the module name and file path determines that this approach is optimal, and multiple modules and files are optimized by the optimizer. Avoid the circular dependencies of the module, if you can't avoid it, you can add a dependency to the "Require" module in the module, and use it directly in the code.

Require ("Dependencymodulename")

Configure Requirejs:

In the previous introduction, we seem to have overlooked a basic question, how did the module name come from? When I require a module, how does this module map to a specific JavaScript file? This involves how to configure Requirejs.

The simplest way to load requirejs is as shown in case 2, in which case we did not specify a baseurl and paths to Requirejs, and if passed as shown in case 10, then data-main specifies a name in the current index.html directory and The/js/main.js in the row folder is used as the entry point for the program, and the/JS directory will also serve as the BaseURL when other modules are defined.

Case Nine: Loading require.js

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

Therefore, all the modules in our previous example rely on, can remove "js/", directly write "Student", "class", "Manager" and so on. A more direct way to display the specified BaseURL and paths is to use Require.config to set these parameters. As shown in case 10.

Case 10. Configure Requirejs

 <script type= "Text/javascript" src= "/js/require.js" ></script> <script type= " 
 text/javascript" > 
 require.config ({ 
  baseurl: "./js", 
  paths: { 
    "some": "Some/v1"
  }, 
 waitseconds:10 
 } ); 
 Require (["Some/module", "My/module", "./js/a.js"], 
  function (Somemodule,  mymodule) {} 
 ); 
 </script>

BASEURL Specifies the base URL for all modules, such as the script loaded by "My/module" is actually/js/my/module.js. Note that a file that ends with. JS does not use the BaseURL, and they still load with the relative path of the current index.html, so add "./js/". If BaseURL is not specified, the path specified in Data-main is used.

The path defined in paths is used to replace the path in the module, as in the previous example some/module the specific JavaScript file path is/js/some/v1/module.js. WAITSECONDS Specifies the maximum number of wait times to load a JavaScript file, which defaults to 7 seconds if the user does not specify it.

Another important configuration is packages, which can specify other directory structures that conform to the COMMONJS AMD specification, resulting in extensive scalability. Modules such as Dojo, JQuery, and so on can also be configured to allow Requirejs to load.

Other configurable options include locale, context, deps, and callback, and interested readers can check the documentation at Requirejs's official website.

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.