Simple implementation of JavaScript asynchronous module loading

Source: Internet
Author: User

JavaScript does not have a module concept similar to Java or other languages, so it is not possible to use keywords such as import or using to refer to modules, which leads to confusing front-end code in complex projects, variable interaction, and so on.

So introducing AMD's concept into complex projects, AMD: The full name is the asynchronous module Definition, the asynchronous module loading mechanism. With AMD it is not necessary to manually add <script> to the page to refer to the script, and by defining dependencies to automatically load the module script, the next code will explain how to implement the proposed AMD module, if you need to see a more detailed implementation can download Requirejs source code.

Simple to achieve the overall idea:

1. Store module name and module file address in memory

2. The module name and module dependencies and module implementation code are stored in memory via the Define method

The 3.require method uses the Loadscript method to import the module code that needs to be dependent and executes the Define method into memory, which is passed into the actual code by the input parameter, thus completing the module loading.

1. Define the module:

Implement the definition of the module and store the module definition.

           /* * * *            @param ID module name             * @param deps Dependent module             * @param factory module             Implementation */  function (ID, deps, factory) {              

In the definition module, the module name, module dependencies and module code are stored in memory.

           /** * * @param ID Module name * @param deps Dependent module * @param factory module implementation */define:function(ID, deps, factory) {//whether the module exists                if(Modules[id])Throw NewError ("module:" + ID + "already exists! "); if(Arguments.length > 2) {Modules[id]={id:id, deps:deps, factory:factory }                }                Else if(Arguments.length = = 2) {Modules[id]={id:id, factory:deps}} Else {                    Throw NewError ("module: parameter is wrong! "); }            },

2. Reference module:

Enter the dependent module name, execute the code, and the code example is as follows:

           /* *            Async Import Module             * @param deps Dependent module             * @param callback            * @returns {{}}            */ function (  deps, callback) {                //  Insert Script deps                              = [].slice.call (Deps);                 // Get dependent script                 loadscript(Deps, Buildmodule, callback);            },

Detailed steps:

You first need to import the script from the dependent folder,

        /** * FROM external load JS * @param deps Dependent module * @param buildmodule Create module method * @param callback */        function loadscript(Deps, Buildmodule, callback) {varDepjscounter = 0; Deps.foreach (function(DEP) {varScript = document.createelement ("Script") Script.type= "Text/javascript"; SCRIPT.SRC=CONFIGS[DEP]; document.getElementsByTagName ("Head") [0].appendchild (script); Script.onload=function () {                    //Dependent JS load Count flagdepjscounter++; if(Depjscounter = =deps.length) { buildmodule(Deps, callback) ();            }                };        }); }

Build the module, remove the dependent module from the global module, inject the dependent module into the existing module as the input parameter, and finally execute the existing module

        /** * Create module * @param deps dependent module * @param callback * @returns {Function}*/        varBuildmodule =function(Deps, callback) {return function () {                //Get dependent module                varargs = []; Deps=[].slice.call (Deps); Deps.foreach (function(DEP) {varmodule =MODULES[DEP]if(typeofModule.factory = = = ' function ') Module.factory=module.factory (); Args.push (Module.factory)})//injecting a dependent module into the callback                vartemp = {};                Callback.apply (temp, args); returnTemp}}

3. Registering the module

The registration module mainly associates the name with the file path, so it is easy to download JS from the path, the code listing is as follows:

           /** * Register module * @param obj*/Config:function(obj) {varPath =obj.paths;  for(varElinchpath) {Object.defineproperty (configs, El, {enumerable:false, Configurable:false, writable:true, Value:path[el]}) }            }        }

4. Execution examples

Writing modules

function () {    var module1 = {};     function () {        return ' Hello Module1 ';    }     return Module1;});

Save the Code JS file and name Module1

Create a new HTML file, register the module in HTML, import the module via require, and write code using the module

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title></title>    <Scriptsrc= "/demo/01requirejs/require.js"></Script></Head><Body></Body></HTML><Script>Require.config ({paths:{module1:'/demo/01requirejs/module1.js'}}); Require (['Module1'],function(Module1) {alert (Module1.sayhello ());})</Script>

Simple implementation of JavaScript asynchronous module loading

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.