Window resize and scroll events

  • 2020-03-30 02:43:48
  • OfStack

My colleague used the scroll event to load the data in the project, which resulted in the tragedy of IE. Give a simple optimization method, the effect is obvious.

Whenever the user changes the window size, some internal element sizes are recalculated, which can cause the entire page to be rerendered, resulting in a significant CPU consumption. For example, if the resize method is called, the user will be constantly triggered when changing the window size, and the lower version of IE may fall into suspended animation. The same is true of the window's scroll event. If the mouse scrolls or drags the scroll bar, the scroll event will be triggered repeatedly.

The basic optimization idea is to execute the resize event function only once in a certain amount of time.
 
var resizeTimer = null; 
$(window).on('resize', function () { 
if (resizeTimer) { 
clearTimeout(resizeTimer) 
} 
resizeTimer = setTimeout(function(){ 
console.log("window resize"); 
}, 400); 
} 
); 

The same is true for scroll event optimization.

Related articles: