The origin of lazy loading function
The concept of lazy loading functions was first seen in the book " Advanced programming of JavaScript"; Sometime last year, I accidentally turned to this chapter; it suddenly felt quite reasonable. Lately, we've always been exposed to Ajax, and we know that differences in behavior between browsers cause us to use Ajax, especially when creating XHR objects, using a lot of if judgments to do compatibility processing. So chew again carefully, write a blog to share once again enhanced.
Common Creation XHR the object in the same way as the following code:
//Create Xhr Object Function createxhr () {if (typeof xmlhttprequest != "undefined") {console.log ("XMLHttpRequest, I was returned once");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 "];var length = versions.length;for (var i = 0; i < length; i++) {try {new activexobject (Versions[i]); arguments.callee.activeXString = versions[i];break;} catch (ex) {//todo something}}}console.log ("ActiveXObject, I was returned once");return new ActiveXObject (arguments.callee.activeXString);} else {throw new error ("no xhr object available.");}}
I don't know, have you noticed that every time we call CREATEXHR, the logic of the entire code goes through it until the browser supports an object and then returns. (Throws an error if none).
Test as follows:
var xhr = createxhr (), var xhr2 = createxhr (); var xhr3 = CREATEXHR ();
Results such as:
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/6E/BF/wKiom1WELsLRQWLHAAKJb5RmqoY736.jpg "title=" Lazy loading 1.jpg "alt=" Wkiom1welslrqwlhaakjb5rmqoy736.jpg "/>
If, an application inside calls the 50,100 times createxhr is not will follow the above logic to walk 50,100 times. In fact, we should think that if the browser support, it will always support, then our large number of if testing is not necessary, even superfluous. From the performance point of view, there is no if condition judgment is certainly faster than containing if judgment;
Of course, the code above has been optimized. What do you say?
in the code above, we consciously put judgment the XMLHttpRequest object is placed in the if first, because we know that most browsers support XMLHttpRequest, and naturally enter the if logic to return XMLHttpRequest, you do not have to proceed with the if judgment. Of course, if you put XMLHttpRequest in the first place, even at the end, it will increase if judgment, the natural performance is worse than the first place. So, when we do the browser function detection, we often put the majority of browser support to the judgment in the first place.
The code might look like this:
function Issupport (feature) {if () {//compatible with most browsers//todo something} else if () {//compatible with a small number of browsers//todo something} else if () {//j very few Browser//todo Something} else {//todo something}}
It 's a little far away, we're back. In order to make less if logical judgments, or not even to do it, we need to use functions to implement so-called "lazy loading Functions".
Lazy Loading function best practices ( 1 )
Lazy loading, which indicates that a branch entry for a function execution occurs once. There are almost two ways of implementing lazy loading.
When a function is called, the function is processed again; What do you mean, during the first call to a function, the function is overwritten with the handler of another branch, so that any call to the function again does not have to test, judge, execute the code of the relevant branch again.
created above XHR , you can override this by using the first "lazy load" method.
The code is as follows:
The first form of lazy loading function createxhr () {if (typeof xmlhttprequest != "undefined") {console.log ("XMLHttpRequest, I was returned once");createxhr = function () {return new xmlhttprequest ();}} else if (typeof activexobject != "undefined") {console.log ("ActiveXObject, I was returned once "); Createxhr = function () {if (typeof arguments.callee.activexstring != "string") {var versions = ["msxml2.xmlhttp.6.0", "msxml2.xmlhttp.3.0", " MSXML2. XMLHttp "];var length = versions.length;for (var i = 0; i < length; i++) {try {new activexobject (Versions[i]); arguments.callee.activeXString = versions[i];break;} catch (ex) {//todo something}}}return new activexobject ( arguments.callee.activeXString);}} else {createxhr = function () {throw New error ("no xhr object available."); &NBSP;}}RETURN&NBSP;CREATEXHR ();}
The above code,if each branch of the createxhr variable is copied, rewritten; the last step of the key is to return the function that called the new copy. So the next time we call createxhr , we call the copy flushing function directly, without having to return the If judgment again.
You can try this call next.
The code is as follows:
var xhr = createxhr (), var xhr2 = createxhr (); var xhr3 = CREATEXHR ();
Results such as:
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/6E/BF/wKiom1WEL9vxzaUCAAG2LXZi7wE077.jpg "title=" Lazy loading 2.jpg "alt=" Wkiom1wel9vxzaucaag2lxzi7we077.jpg "/>
Lazy Loading function best practices ( 2 )
The second way to implement lazy loading is to declare a function and retain the self-executing function to return the specified function. This is designed to function self-execution is the loss of a bit of performance to do functional detection; The first call, or the nth call, does not have to do function detection, the performance loss is minimized.
we rewrite createxhr again.
The code is as follows:
The second type of lazy loading var createxhr = (function () {if (typeof xmlhttprequest != "Undefined") {console.log ("XMLHttpRequest, I was returned once"); return function () {return New xmlhttprequest ();}} else if (typeof activexobject != "undefined") {console.log ("ActiveXObject, I was returned once "); Return function () {if (typeof arguments.callee.activexstring != " String ") {var versions = [" MSXML2. xmlhttp.6.0 ", " MSXML2. xmlhttp.3.0 ", " MSXML2. XMLHttp "];var length = versions.length;for (var i = 0; i < length; i++) {try {new activexobject (Versions[i]); arguments.callee.activeXString = versions[i];break;} catch (ex) {//todo something}}}return new activexobject ( arguments.callee.activeXString);}} else {return function () {throw new&nbsP Error ("no xhr object available."); }}) ();
Then we call, the code is as follows:
var xhr = createxhr (), var xhr2 = createxhr (); var xhr3 = CREATEXHR ();
as expected, the call was made three times without performing the IF function detection.
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/6E/BB/wKioL1WEMxDyjhyOAAK92RMsFWU343.jpg "title=" Lazy loading 3.jpg "alt=" Wkiol1wemxdyjhyoaak92rmsfwu343.jpg "/>
Well, the code I do not explain more, I believe that can calm down to see the friends here, must have been very familiar with closures, function self-implementation and so on.
Written in the last
"Lazy Loading" is an advanced technique that follows the previous blog, "Scope-safe constructors". The advantage is that only a bit of performance is lost in the first execution of the code for functional detection. Which of the above two ways is more suitable for you, depends on you.
This article is from the "Shuizhongyue" blog, make sure to keep this source http://shuizhongyue.blog.51cto.com/7439523/1663739
Lazy Load function