Later, a technical group asked about the following piece of code:
function html2node(s) {
var d = document.createElement('div');
d.innerHTML = s;
if (d.childNodes.length == 1)
return d.childNodes [0];
var df = document.createDocumentFragment();
while (d.firstChild)
df.appendChild(d.firstChild);
return df;
}
I understand the general principles, but what is more confusing is why document.createDocumentFragment is used?
After searching for relevant resources on the Internet, I found out that document.createDocumentFragment is used to create document fragments.
When we need a large number of appendChild page elements, we can first appendChild these elements into document.createDocumentFragment.
Then just appendChild the document fragment to the page. This eliminates the need to refresh the page multiple times to achieve performance optimization. I think the use of document fragments in the above code is redundant.