SoFunction
Updated on 2025-04-10

Basic optimization ideas for window resize and scroll events

My colleagues used scroll events to load data in the project, but IE was in a tragedy. A simple optimization method is given, and the effect is obvious.

As long as the user changes the window size, some internal elements will be recalculated, which may cause the entire page to be re-rendered and eventually lead to a large amount of CPU consumption. For example, when calling the resize method, the user will be triggered constantly when changing the window size, and the lower version of IE may fall into a fake death state. The same is true for the scroll event of the window. If the mouse scrolls or drags the scrollbar, the scroll event will be triggered continuously. If there are too many things to handle, the lower version of IE will also fall into a fake death state.

Basic optimization idea: only execute the resize event function once within a certain period of time.
Copy the codeThe code is as follows:

var resizeTimer = null;
$(window).on('resize', function () {
if (resizeTimer) {
clearTimeout(resizeTimer)
}
resizeTimer = setTimeout(function(){
("window resize");
}, 400);
}
);

Scroll event optimization is the same.