Tuesday, August 16, 2022

Web APIs — Document. createDocumentFragment() | Range.createContextualFragment()

The Document.craeteDocumentFragment() API creates a new empty document fragment (DocumentFragment) object. The document fragment is a lightweight container for creating HTML elements, an alternative to directly inserting elements into the DOM.

Instead of appending the elements directly to the document when they are created, append them to the DocumentFragment instead, and finish by adding that to the DOM. This is extremely helpful because most manipulations of DOM elements cause the browser to reflow and repaint the layout, which you want to reduce to a minimum. This is because the nodes created by the CreateDocumentFragment method are not part of the DOM; they reside in memory.

When you need to add a lot of nodes to Document, Adding them one by one in sequence may result in many calculations, such as adjusting the screen’s position each time(reflow). Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element’s position and geometry)

When we append the document fragment to the DOM, it is basically replaced by its children, i.e., there is no document fragment appended to the document; only its children get appended, but when we append the element to the DOM, the parent is also appended to the document.

<!DOCTYPE html>
<html>
<body>
<h1>Add items to an empty list: using The createDocumenFragment() Method</h1><ul id="browsers">
</ul>
<script>const browsers = ['Firefox', 'Chrome', 'Opera','Safari', 'Internet Explorer'];// Create a document fragment:
const dFrag = document.createDocumentFragment();
for (let x in browsers) {
const li = document.createElement('li');
li.textContent = browsers[x];
dFrag.appendChild(li);
}
// Add fragment to a list:
document.getElementById('browsers').appendChild(dFrag);
</script>
</body>
</html>

The createDocumentFragment() method can also extract parts of a document, change, add, or delete some of the content, and insert it back into the document.

createContextualFragment:

The createContextualFragment method is helpful if you want to create a DocumentFragment object with initial content. If you’re going to build a DocumentFragment object from the contents of a Range object

<!DOCTYPE html>
<html>
<body>
<h1>createContextualFragment()</h1><div id="parent"></div><script>var html='<div>Test1</div><span>Test2</span>';
const fragment = document.createRange().createContextualFragment(html);
document.getElementById('parent').appendChild(fragment);
</script></body>
</html>


No comments:

Post a Comment