JavaScript code Tutorial: Lazy Load function

Source: Internet
Author: User
Tags object contains execution return string versions

Article Introduction: because of the differences in behavior between browsers, most JavaScript code contains a large number of if statements that boot the execution into the correct code. Look at the CREATEXHR () function in the XMLHttpRequest (XHR) object.

Because of the differences in behavior between browsers, most JavaScript code contains a large number of if statements that boot the execution into the correct code. Look at the CREATEXHR () function in the XMLHttpRequest (XHR) object:

function createxhr () {if (typeof XMLHttpRequest!= "undefined") {return new XMLHttpRequest
    ();
            else if (typeof activexobject!= "undefined") {if (typeof arguments.callee.activeXString!= "string") {
            var versions = ["msxml2.xmlhttp.6.0", "msxml2.xmlhttp.3.0", "msxml2.xmlhttp"]; for (var i = 0, len = versions.length i < len; i++) {try {new Activexobect (versi
                    Ons[i]);
                    arguments.callee.activeXString = Versions[i];
                Break The catch (ex) {//Skip}}} return to new Activexobect (argument
    s.callee.activexstring);
    else {throw new Error ("No XHR object available."); }
}

Every time createxhr () is invoked, it is carefully checked for the capabilities that the browser supports. Check the built-in XHR first, then test for XHR based on ActiveX, and then throw an error if you don't find it. This is done every time the function is invoked, even if the results of the branch are constant at each call: if the browser supports built-in XHR, then it is supported, and the test becomes unnecessary. Even if the code for an if statement is certainly slower than without the IF statement, the code can run faster if the IF statement does not have to be executed every time. The solution is a technique called lazy loading.

Lazy loading represents a branch of a function execution that occurs only once: the first time the function is called. In the first call, the function overrides another function that executes in the appropriate way, so that any calls to the original function do not have to be executed. For example, you can use lazy load overrides createxhr () in the following ways:

function Createxhr () {if (typeof XMLHttpRequest!= "undefined") {createxhr = function () {retur
        N new XMLHttpRequest (); } else if (typeof activexobject!= "undefined") {createxhr = function () {if (typeof arguments . callee.activexstring!= "string" {var versions = ["msxml2.xmlhttp.6.0", "msxml2.xmlhttp.3.0", "msxml2.x
                Mlhttp "]; for (var i = 0, len = versions.length i < len; i++) {try {var xhr = new
                        ActiveXObject (Versions[i]);
                        arguments.callee.activeXString = Versions[i];
                    return XHR; catch (ex) {//Skip}} return to new A
        Ctivexobect (arguments.callee.activeXString);
        } else {createxhr = function () {throw new Error ("No XHR object available.");
    };
  }  return createxhr (); }

In this lazy-loaded createxhr (), each branch of an if statement assigns a value to the CREATEXHR variable, effectively overwriting the original function. The final step is to invoke the newly assigned function. The next time you call CREATEXHR (), the assigned function is called directly, so that you do not have to call the IF statement again.

The lazy load function has two primary somewhat. First, the appropriate code to execute occurs only when the function is actually called. Some JavaScript libraries start with a lot of code branching out of browser capabilities or quirks, and everything is set up first. Lazy loading delays these computations as much as possible, guaranteeing the right functionality without affecting the execution time of the initial script. Second, although the first call to the function is slightly slower because of the extra second function call, all subsequent calls are faster, since multiple if conditions are avoided.



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.