我遇到了一個有趣的問題,這可能是瀏覽器相關(但我不確定)。我正在研究一個非常大的網頁,這是一個文字處理器風格的應用程序。我有這樣的結構:
<article>
<div>...</div>
<div>...</div>
<div>...</div>
... 5000 more divs ...
</article>
當我第一次加載頁面時,我有一個函數做兩件事。首先,分析使用正則表達式的每個div的HTML的內容和一類適用於DIV是否匹配特定的正則表達式,從而導致這樣的事情:
<article>
<div class="type1">...</div>
<div class="type2">...</div>
<div class="type3">...</div>
... 5000 more divs ...
</article>
功能的第二部分則計算出的高度每個div並將其添加到計數器。一旦它通過一定數目,我插入了一段HTML充當分頁符,然後用清水沖洗,重複:
// Pagination variables
var document_current_page_height = 0;
var constant_default_page_height = 1000;
var page_number = 0;
// Iterate over page elements
object_range.each(function()
{
// Check whether page is too long
if (document_current_page_height + $(this).outerHeight(true) > constant_default_page_height)
{
// Create page break
$(this).before("<section contenteditable=\"false\"><h3 class=\"page-footer\">" + document_page_footer" + "</h3><figure><hr /><hr /></figure><h1 class=\"page-header\">" + document_page_header + "</h1><h2 class=\"page-number\">" + page_number + "</h2></section>");
// Adjust variables
page_number++
document_current_page_height = 0;
}
// Increment current page height
document_current_page_height += $(this).outerHeight(true));
});
此代碼的工作完美,但這裏的問題...
運行時因爲它應該運行,大約需要2秒。但是,如果我運行相同的代碼,但跳過了流程的第一部分(將類添加到div),代碼將在0.2秒內運行。
我進一步通過評論$(this).before
代碼行來隔離問題。完成後,兩個速度測試都接近相同(100ms內)。
我沒有得到的是,$(this).before
代碼行沒有引用div的高度/樣式/類,那麼爲什麼divs有一個類時的延遲?
這僅僅是瀏覽器在他們有課時掙扎在div上的一個例子嗎?有什麼想法嗎? (我正在使用Safari 9.1)。
謝謝!