Dynamic loading technology of objects in JavaScript

Source: Internet
Author: User
Tags constructor eval extend html page

What is JavaScript object dynamic loading

JavaScript dynamic loading (JavaScript Object dynamic Loading)-called dynamic, should be different from the usual static loading form.

The typical JavaScript static loading method is to embed all the JS files we may need into an HTML page by <script> tag, and when the browser executes to the <script> tag, Will go to our designated place to load JavaScript and run, at which point the file is defined regardless of method, class, object, etc., already exists with the browser, waiting to be used. These things persist unless the HTML page is unload.

And the typical dynamic loading mode, is not required any advance preparation, only when you need a JavaScript object to serve us, we temporarily to load it belongs to the JS file, and then use it, use finished, destroy can. It is called "to come, to go".

Because of the ability to "come and go," it makes JavaScript truly alive.

JS dynamic load solves what problem

    • Lose weight to the system: you can delay loading unnecessary JavaScript code, unused functionality does not load.
    • Modularization to achieve: can be the original block of functions or classes, decomposed into a reasonable small block, easy to manage and maintain.
    • Convenient value transfer: Bidirectional transfer value, without restraint. Based on JSON, you can pass large objects.
    • Can implement service: can be based on service concept, through the core JavaScript object to use other services to the object, complete the business assembly.

JS dynamic load should have what ability

    • Can be asynchronous, or synchronized, the heart of the encounter loading external JS file.
    • The contents of the loaded JS file can be effectively managed, including scope, openness, and lifecycle.
    • Object-oriented, object based rather than method or variable can be supported.
    • There is a good encapsulation, you can operate the entire loaded JS through a handle.

Implementation of traditional JS dynamic loading

About the implementation of JS dynamic loading, I have seen many ways. In the early days, people thought about many ways. These methods have their own space to play, can solve some problems. However, there are more or less drawbacks, and the implementation of the cumbersome, the biggest problem is that they are basically not object-oriented. The main 2 categories are listed below:

    • Use nested iframe to load JS files: This way the most early, by including an IFrame in the page, to call a second contains the <script> tag HTML page, to achieve the dynamic load JS. The biggest drawback is the inability to pass parameters, the implementation of more cumbersome.
    • Create <script> label temporarily: This way is used by many people. Use JavaScript to manipulate the page Dom model, temporarily create a <script> tag, then appendchild to <body>, or dynamically change the SRC attribute of the existing <scirpt> tag. The disadvantage is that only synchronous loading, you must wait for the JS file is read completed before the next work. The transfer value is realized by calling the variables in the JS, and the bidirectional transfer value is difficult and the scope is weakened.

We can see that these two common ways, are unable to meet our requirements.

More Excellent solutions

Thanks to the magic like Aladdin's Magic Lamp eval (), we can achieve all of the above desire:).

I've been around so much and thought so many ways. In fact, the simplest way is under the nose.

First part-caller Main.js file:

//The method for dynamically reading a JS object

//@FileName: The JS object URL to read, which can be a local path.

//@TheParameters: Parameters that need to be passed to the loaded object, can be any object.

Function Loadjsobj (filename,theparameters) { 
    Ext.Ajax.request ({  // Asynchronous Call method  
        url:filename,  //Call url 
         scope:this,   
         Success:function (response) {  //Successful callback method response for return content
             var remoteobj = eval (response.responsetext);  
             var mod = null; 
             mod = new Remoteobj (theparameters);

            return mod; 
        }, 
        failure:function () {  //Failed callback method  
             alert (name+ '-read failed, check your network or file. ');

            return null; 
        } 
   });  
}

This code uses the asynchronous Read Method Ext.Ajax.request () encapsulated by the ExtJS class library. Just for convenience. It's OK if you use an XMLHttpRequest object.

The first thing to say about the Loadjsobj method is:

    • With XMLHttpRequest to an AJAX request, will want to load the JS file source code read over.
    • Use the Eval function to instantiate the remote JavaScript class that you just read as a local object (during which the constructor parameters were passed).
    • Returns this object for use.

The key code here is

var remoteobj = eval (response.responsetext);
var mod = null;
MoD = new Remoteobj (theparameters);

return mod;

As you can see, we directly pass the read JS file into the eval function. And return a thing called remoteobj, this thing is actually read JS handle (a class, defined in the Read JS class, later will be described in detail), through the Remoteobj instantiation, that is, mod = new Remoteobj (parameters) can be through the MoD object to be read JS arbitrary operation.

As a result, the remote JS is by our parameters specified in the request instantiated into the local object, you can use. But... It's just wishful. Because the read JS to meet our requirements, in order to "consensual" and finally get results ...

Part Two-callee login.js file:

To meet the requirements, the read JS file must also be written in accordance with certain rules.

//User logon class

Ext.extend (eueuy.module,{ 
    init:function () {   &NBSP;&NBSP
       //==variables==// 
         var userName = this.parameters.un; //Get the parameters passed in un 
         var PassWord = this.parameters.pwd;  //Get the parameters passed in pwd 
      &NBSP;&NBSP
       //==methods==// 
        //Login method  
        function Loginon () { 
             if (username== ' Eueuy ' | | | | password== ' 123 ') { 
                return true;                 
           }else{ 
                 return false; 
            } 
       } 
       //Logout method         
         function Loginoff () { 
             alert (' welcome again ');

       } 
   } 
});

Let's take a look at what this login class does:

    • Inherits from the Eueuy.moudle and overrides the constructor.
    • Received 2 initialization parameters passed in, UN and pwd.
    • 2 member methods and one member variable are defined.

There is no special thing, is the Ext.extend method used a bit strange, different from the usual XXX = Ext.extend ();

There are no assignment symbols and class names. This is precisely a key point:

The name of the class must be left blank

Why do you write that? Because of this, this class with no class name can then define the class name when the eval () function executes him, thus leaving the definition of the class name at the time of invocation, which is the Main.js file. This trick will also allow callers (main.js) to directly control the class of the callee (login.js).

Finally, the following code can be used in main.js to perform user logon verification by dynamically loading the user login class:

var Loginmodel = Loadjsobj (', {un: ' Eueuy ', pwd: ' 123 '});

if (Loginmodel.loginon ()) {

Alert (' Login successful, welcome ' +loginmodel.username ');

}else{

Alert (' Login failed, wrong username password ');

}

As you can see, in the above code, we control the login class in Login.js by Loginmodel this variable, we can access the method Loginon (), and we can access the variable userName.

End

So far, the theory of object dynamic loading technology has been explained almost, and in the next blog post, I will also be based on these theories, to give you a dynamic loading of the project framework. This framework can facilitate the implementation of one-page, but also can see some specific applications.

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.