JavaScript is an optimization mode-branch during initialization and javascript Initialization
During initialization, the Branch is an optimization mode. When you know that a condition will not change throughout the life cycle of the program, it makes sense to test the condition only once. browser sniffing is a typical example.
2. Finding out the calculation style of DOM elements or the additional event handler is another scenario that can benefit from the branch mode during initialization. Example:
Before optimization:
var utils ={ addListener:function(el,type,fn){ if(typeof window.addEventListener ==='function'){ el.addEventListener(type,fn,false); } else if(typeof document.attachEvent ==='function'){ el.attachEvent('on'+type,fn); } else{ el['on'+type]=fn; } }, removeListener:function(el,type,fn){ if(typeof window.removeEventListener ==='function'){ el.removeEventListener(type,fn,false); } else if(typeof document.detachEvent ==='function'){ el.detachEvent('on'+type,fn); } else{ el['on'+type]=null; } }};
The above code is inefficient. Every time you call utils. addListener () or utils. during removeListener (), the same check is performed repeatedly. If the branch is used during initialization, browser features can be detected at one time during script initialization and loading. In addition, you can redefine the function running mode throughout the lifecycle of the page. As follows:
var utils = { addListener:null, removeListener:null};if(typeof window.addEventListener ==='function'){ utils.addListener=function(el,type,fn){ el.addEventListener(type,fn,false); }; utils.removeListener=function(el,type,fn){ el.removeEventListener(type,fn,false); };} else if(typeof document.attachEvent ==='function'){ utils.addListener=function(el,type,fn){ el.attachEvent('on'+type,fn); }; utils.removeListener=function(el,type,fn){ el.detachEvent('on'+type,fn); };} else{ utils.addListener=function(el,type,fn){ el['on'+type]=fn; }; utils.removeListener=function(el,type,fn){ el['on'+type]=null; };}
When using this mode, do not over-assume browser features.