background

In the development process, sometimes you need to check the browser environment, for example, when encapsulating a function that can get the element style, you need to write a function to check, but the normal writing method is a bit cumbersome, will check many times, but the browser environment is fixed, only need to check once. This results in the browser wasting too much time checking the function again every time it is called. This is where lazy functions are used to solve the problem

The inertia function

  • For optimizing frequently used functions
  • Due to the differences between major browsers, we need to consider the compatibility between different browsers when implementing a function, so browser sniffing is required
  • Lazy loading the branch that represents the execution of a function is executed only when the function is dropped for the first time. During the first call, the function is overwritten with another function that executes properly, so that any calls to the original function do not have to go through the execution branch again.

The instance

  • There are two ways to get an element style:
    • GetComputedStyle ([element object]) is incompatible with IE6-8
    • [Element object]. CurrentStyle has no compatibility issues
function get_css(element,attr){
	// Execute the function for the first time to refactor the external get_CSS based on browser compatibility
		if('getComputedStyle' in window){
			get_css=function(element,attr){
				return window.getComputedStyle(element)[attr]
			}
		}
		else{
			get_css=function(element,attr){
				return element.currentStyle[attr];
			};
		}
		// Execute the refactored function once
		return get_css(docment,attr)
	}
	var w=get_css(docment.body,'width');
	// Execute the following function, execute the small method after the first reconstruction, no need to check compatibility
	var h=get_css(docment.body,'height');
Copy the code

The get_CSS function takes two arguments, one for the element itself and one for the style attribute. When executing the function for the first time, check whether the getComputedStyle is on the window. If not, the current environment is IE6-8. If this function is used heavily in your project, executing the entire function without making this judgment each time can cost performance. At this point, the use of lazy functions is particularly important, the first time to determine the current browser environment, the next time to call the function, no need to judge, the function is refactored to optimize its performance.