減少DOM數可以加快瀏覽器的在解析頁面過程中DOM Tree和render tree的構建,從而提高頁面性能。為此我們可以把頁面中那些首屏渲染不可見的部分HTML暫存在TextArea中,等完成渲染后再處理這部分HTML來達到這個目的。 要把TextArea 中暫存的HTML內容添加到頁面中,使用元素的outerHTML屬性是最簡單方便的了,不過在DOM標準中并沒有定義outerHTML,支持的瀏覽器有IE6+,safari, operal和 Chrome,經測試FF4.0- 中還不支持。所以我們就來實現一個可以跨瀏覽器的outerHTML。 
outerHTML 就是獲取或設置包含元素標簽本身在內的html。下面是實現代碼: 
 代碼如下: 
if(typeof HTMLElement !== "undefined" && !("outerHTML" in HTMLElement.prototype)) { 
//console.log("defined outerHTML"); 
HTMLElement.prototype.__defineSetter__("outerHTML",function(str){ 
var fragment = document.createDocumentFragment(); 
var div = document.createElement("div"); 
div.innerHTML = str; 
for(var i=0, n = div.childNodes.length; i<n; i++){ 
fragment.appendChild(div.childNodes[i]); 
} 
this.parentNode.replaceChild(fragment, this); 
}); 
// 
HTMLElement.prototype.__defineGetter__("outerHTML",function(){ 
var tag = this.tagName; 
var attributes = this.attributes; 
var attr = []; 
//for(var name in attributes){//遍歷原型鏈上成員 
for(var i=0,n = attributes.length; i<n; i++){//n指定的屬性個數 
if(attributes[i].specified){ 
attr.push(attributes[i].name + '="' + attributes[i].value + '"'); 
} 
} 
return ((!!this.innerHTML) ? 
'<' + tag + ' ' + attr.join(' ')+'>'+this.innerHTML+'</'+tag+'>' : 
'<' + tag + ' ' +attr.join(' ')+'/>'); 
}); 
} 
 
代碼說明: 
1 代碼中首先條件判斷來監測瀏覽器是否支持outerHTML以避免覆蓋瀏覽器原生的實現。 
2 "__defineSetter__","__defineGetter__" 是firefox瀏覽器私有方面。分別定義當設置屬性值和獲取屬性要執行的操作。 
3 在"__defineSetter__" "outerHTML"中為了避免插入頁面中元素過多導致頻繁發生reflow影響性能。使用了文檔碎片對象fragment來暫存需要插入頁面中DOM元素。 
4 在"__defineGetter__" "outerHTML" 中使用元素attributes屬性來遍歷給元素指定的屬性。結合innerHTML返回了包含原屬本身在內的html字符串。 
測試代碼: 
 代碼如下: 
<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<title>outerHTML</title> 
</head> 
<body> 
<div id="content" class="test"> 
<p>This is <strong>paragraph</strong> with a list following it</p> 
<ul> 
<li>Item 1</li> 
<li>Item 2</li> 
<li>Item 3</li> 
<li>Item 4</li> 
</ul> 
</div> 
<script> 
if(typeof HTMLElement !== "undefined" && !("outerHTML" in HTMLElement.prototype)) {             
新聞熱點
疑難解答
圖片精選