今天讀vue源碼,讀到了fragment攻询。抱著一直以來的好奇从撼,打開了mdn文檔,只能說“又學(xué)習(xí)到了”钧栖。
A DocumentFragment is a minimal document object that has no parent. It is used as a light-weight version of document to store well-formed or potentially non-well-formed fragments of XML.
documentFragment特性
documentFragement可以作為append類(Node.appendChild
,Node.insertBefore
)方法的參數(shù)谋逻,但是只有它的children被append,本身卻不會桐经。
與template的配合
template不會被渲染毁兆,但仍在dom結(jié)構(gòu)樹中,可以通過getElement類方法找到它阴挣。
HtmlTemplateElement.content是documentFragment
利用這一點可以甄別瀏覽器對template的支持
if ('content' in document.createElement('template') {
console.log('HTML template element is supported');
} else {
console.log('the HTML template element is not supported');
}
MDN中非常好的示例
- 獲取template元素
- content中找到需要修改的text或value
- 利用document.importNode或者content.cloneNode克隆得到實例
- 將新實例append進某元素中
性能優(yōu)化
john Resig大神發(fā)現(xiàn)了利用documentFragment優(yōu)化append類操作的途徑气堕。
但是個人感覺documentFragment的設(shè)定就是為了這個,比如這篇文章中談及documentFragment應(yīng)有的使用姿勢