我使用Firefug对我的Web应用程序进行了概要分析,发现实际上每个用户访问都调用了并且需要调用以下函数数百次。因此,我想对其进行优化,因为Firebug说它使用最多的资源/时间。

function highlightChildDiv(parentDiv) {

    /* find the closest (hlisting) home listing to the middle of the scrollwindow & highlight */
    var scrollElemPos = parentDiv.offset();
    var highlightDiv = $(document.elementFromPoint(
        scrollElemPos.left + parentDiv.width()  / 2,
        scrollElemPos.top  + parentDiv.height() / 2)
    ).closest('#parentDiv div.childClass');

    if (highlightDiv.hasClass("HighlightRow")) {
        return; // if the div is already highlighted, return
    } else {
        $('#parentDiv div.childClass').removeClass("HighlightRow");
        highlightDiv.addClass('HighlightRow');
    }
}


在我看来,最未经优化的语句之一是.closest('#parentDiv div.childClass');,但是我敢肯定还有其他事情需要改进。

问题:鉴于此功能实际上每次用户访问要运行数百次,因此有人对我如何优化上面的代码有任何JQuery性能提示。

最佳答案

首先考虑一下,消除if子句中的dead语句。

if (!highlightDiv.hasClass("HighlightRow")) {
    $('#parentDiv div.childClass').removeClass("HighlightRow");
    highlightDiv.addClass('HighlightRow');
}


在选择器#parentDiv div.childClass中,您可以保证div是#parentDiv的直接后代吗?在这种情况下:

.closest('#parentDiv>div.childClass');




$('#parentDiv>div.childClass')


您已经有parentDiv。我猜这是一个DOM对象,因此您可以执行以下操作:

$(parentDiv).children("div.childClass")


只需隐藏当前突出显示的DIV:

$('#parentDiv div.HighlightRow').removeClass("HighlightRow");

关于javascript - JQuery:如何缓存DOM?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2163596/

10-09 19:57