Home > Web Front-end > JS Tutorial > body text

window resize和scroll事件的基本优化思路_javascript技巧

WBOY
Release: 2016-05-16 16:50:37
Original
1613 people have browsed it

同事在项目中使用scroll事件去加载数据,结果IE下悲剧了。给了一个简单优化方法,效果明显。

只要用户改变窗口大小,会对内部一些元素大小重新计算,可能导致整个页面重新渲染,最终导致大量消耗 CPU。比如调用 resize 方法,用户改变窗口大小时会不停的被触发, 低版本的IE 会可能陷入假死状态。window的scroll事件也是如此,鼠标滚动或拖动滚动条,就会不停的触发scroll事件,如果处理的东西多,低版本的IE也会陷入假死状态。

基本的优化思路:在一定的时间之内,只执行一次resize事件函数。

复制代码 代码如下:

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

scroll事件优化同理。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!