[英]JQuery: How to cache DOM?
我使用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");
我更喜歡使用以下方法:
https://gist.github.com/3841424#file-domcache-js
或者,您可以在此實現中用一種方法替換DOM對象:
var myNS = {
myEventHandler: function(event){
this.DOM.$el.doSomething();
},
cacheDOM: function(){
return {
$el: $("#matrix")
};
},
initialize: function(){
this.DOM = this.cacheDOM();
}
};
我的猜測是這是最未優化的行:
$('#parentDiv div.childClass').removeClass("HighlightRow");
您應該對其進行概要分析,以確保(在調用外部創建日期對象,並在每次調用之前和之后輸出getTime()值)。
在這里,您要jQuery遍歷與該選擇器匹配的所有DOM元素並刪除該類。 如果有1000行,則jQuery將需要對每個行進行查詢,以查看是否需要刪除一個類。 啊。 這是刪除查找的地方:
// namespace scoped cache
var Hash_$_Cache = {
$parentDiv : $('#parentDiv'),
$tgt_row : $([]) // empty jq object to start
};
// find the closest (hlisting) home listing to the middle of
// the scrollwindow and highlight
//
var highlightChildDiv = function (parentDiv){
var
scrollElemPos = parentDiv.offset(),
$tgt_row
;
$tgt_row = $(document.elementFromPoint(
scrollElemPos.left + parentDiv.width() / 2,
scrollElemPos.top + parentDiv.height() / 2)
).closest('#parentDiv div.childClass')
;
// bail if row is already highlighted
if ($tgt_row.hasClass('HighlightRow')){ return; }
Hash_$_Cache.$tgt_row.removeClass('HighlightRow');
$tgt_row.addClass('HighlightRow');
// save highlighted row for later
Hash_$_Cache.$tgt_row = $tgt_row; // store new row in cache
};
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.