jQuery滚动事件导致性能问题 [英] Jquery scroll event causing performance issues

查看:86
本文介绍了jQuery滚动事件导致性能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用浏览器滚动事件根据用户滚动的数量放置一个html块.该代码有效,但它引起了一个巨大的性能问题,该问题基本上迫使我的浏览器冻结.

I'm trying to use the browser scroll event to place a block of html based on the amount a user has scrolled. The code works but it is causing a huge performance issue which basically forces my browser to freeze.

任何关于为什么以及我能解决这个问题的见解将不胜感激.

Any insight as to why and what I could do to resolve this would be greatly appreciated.

<script type="text/javascript">

$('#content').scroll(function () {
    var scroll = $('#content').scrollTop();
    var $controls = $(".controls").clone();
    if (scroll > 200) {
        $(".controls").remove();
        $('#header').append($controls);
    }
    else {
        $(".controls").remove();
        $('.banner').append($controls);
    }
});

</script>

推荐答案

首先,发现DOM中的元素是一项昂贵的活动,因此请缓存jQuery对象.

First, discovering elements in the DOM is an expensive activity, so cache your jQuery objects.

第二,.append()移动元素,因此.clone()remove()应该是不必要的.

Second, .append() moves elements around so .clone() and remove() should be unnecessary.

这给出了:

var $$ = {//cache of jQuery objects
    content: $('#content'),
    controls: $(".controls"),
    header: $("#header"),
    banner: $('.banner')
};
$('#content').scroll(function() {
    $controls.appendTo(($$.content.scrollTop() > 200) ? $$.header : $$.banner);
});

现在,您可以减少调用处理程序的频率,可以通过以下方式实现:

Now, you can work on reducing the frequency at which the handler is called, which can be achieved as follows :

var $$ = {//cache of jQuery objects
    content: $('#content'),
    controls: $(".controls"),
    header: $("#header"),
    banner: $('.banner')
};

var scrollHandling = {
    allow: true,
    reallow: function() {
        scrollHandling.allow = true;
    },
    delay: 50 //(milliseconds) adjust to the highest acceptable value
};

$('#content').scroll(function() {
    if(scrollHandling.allow) {
        $controls.appendTo(($$.content.scrollTop() > 200) ? $$.header : $$.banner);
        scrollHandling.allow = false;
        setTimeout(scrollHandling.reallow, scrollHandling.delay);
    }
});

这篇关于jQuery滚动事件导致性能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆