javascript add element add element with DocumentFragment

Keywords: Fragment Windows Mac Linux

Insert node

When we want to insert a single node, we can use the insertBefore() and appendChild() methods. If we want to insert multiple content, we need to use DocumentFragment. It is a strategy to use the insertion method repeatedly, but in this way, the browser will render the DOM tree continuously, which will affect the user experience.

Document fragment, which is a document fragment in Chinese, can be understood as a lightweight node, and multiple sub elements can be added to it. NodeType = 11, nodeName = ා document fragment. It is used as a warehouse. It is usually invisible in the DOM tree and hidden. If we want to add multiple elements, we temporarily store them all in this warehouse, and then take them out and put them into the DOM tree at one time, so that we won't render the page repeatedly.

In other words, to solve this problem at one time, temporarily find a place to store the nodes we want to add. This place is document fragment

This code gives the method of adding nodes without fragment and adding nodes with fragment, and gives comments.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<h1>Dom Add and delete instances of</h1>
		<ul>
			<li>Add an element</li>
			<li>Add multiple elements</li>
			<li>Delete an element</li>
			<li>Delete multiple elements</li>
		</ul>
		<script>
			var h2=document.createElement('h2');
			var h2text=document.createTextNode('OS list');
			h2.appendChild(h2text);
			document.body.appendChild(h2);
			
			var ul=document.createElement('ul');
			/*var li=document.createElement('li');    //Single creation method
			var litext=document.createTextNode('windows');
			li.appendChild(litext);
			ul.appendChild(li);
			document.body.appendChild(ul);*/
			
			var oslist=['windows','mac','linux'];
			for(var i=0,len=oslist.length;i<len;i++)
			{
				var li=document.createElement('li');
				var litext=document.createTextNode(oslist[i]);
				li.appendChild(litext);
				ul.appendChild(li);     //Because ul in Dom will be updated frequently, which will affect the user experience.
			}
			document.body.appendChild(ul);
			 
			 
			var ul=document.createElement('ul');
			var oslist=['windows','linux','mac'];
			var frag=document.createDocumentFragment();
			for(var i=0,len=oslist.length;i<len;i++)
			{
				var li=document.createElement('li');
				var litext=document.createTextNode(oslist[i]);
				li.appendChild(litext);
				frag.appendChild(li);    //frag is not in DOM and will not be updated frequently.
			}
			ul.appendChild(frag);
			document.body.appendChild(ul);
		</script>
	</body>
</html>

 

Posted by rslnerd on Sat, 21 Dec 2019 12:08:54 -0800