【问题标题】:jQuery filter optimization (slow performance on mobile devices)jQuery 过滤器优化(在移动设备上性能缓慢)
【发布时间】:2016-01-22 14:50:29
【问题描述】:

我有一个大约 200 项的列表(在表格行中):

<tr><td><h5>Title</h5></td>
    <td class="nazwa">some text</td>
    <td>Some additional stuff</td>
</tr>

我创建了一个 jQuery 函数,如果它们与搜索的字符串匹配,它会过滤(显示或隐藏)项目

jQuery.fn.filterItems = function(str){
    var title = jQuery(this).find("h5").text().toLowerCase();
    var name = jQuery(this).find(".nazwa").text().toLowerCase();
    if( title.search( str ) < 0 && name.search( str ) < 0 ){
        jQuery(this).hide().removeClass("visible");
    }
    else{
        jQuery(this).show().addClass("visible");
    }
    return this;
}

每次用户在搜索输入中输入内容时,它都会自动过滤项目并显示与输入匹配的项目:

jQuery("#search_items").on("input", function(){
        var s = jQuery(this).val();
        if(s != ""){
           jQuery('.list-of-items tr').each(function(){
               jQuery(this).filterItems( s.toLowerCase() );
           });
        }
        else{
            jQuery('.list-of-items tr').show().addClass("visible");
        }
    });

这在 PC 上运行良好,但在移动设备上存在一些性能问题。有时输入和过滤器反应之间有相当长的延迟。

如何在性能/资源使用方面优化此实时搜索?

【问题讨论】:

  • 我会使用从 input 到实际过滤器的半秒或秒超时 - 如果用户输入 8 个字符的单词 - 您正在非常快速地执行 8 个过滤器 - 而实际上您只一旦他们完成打字就需要。
  • davidwalsh.name/javascript-debounce-function - 首先看看这个链接(阅读更多关于 jquery debounce 的信息)
  • @stefanz - 我实现了这个解决方案,它似乎有点帮助。请考虑将此建议作为答案,以便我可以接受它作为解决方案,如果 ti 可行的话。

标签: jquery performance search mobile livesearch


【解决方案1】:

这可能会有所帮助:https://davidwalsh.name/javascript-debounce-function。

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

您必须从上面用debounce() 包装事件函数(在您的情况下为input)。

阅读更多关于debounce and throttle的信息

如果你有一个使用 Angular 的项目,它会更容易和更快:https://docs.angularjs.org/api/ng/filter/filter。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-30
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多