Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Template element vs document.createDocumentFragment

I'm trying to figure out the difference between using document.createDocumentFragment versus using an HTML <tamplate> element.

Is there a difference between them in behavior or performance?

like image 309
Mendy Avatar asked Dec 02 '18 06:12

Mendy


1 Answers

Both <template> and document.createDocumentFragment are used for storing HTML-like data without rendering it, but the use cases are somewhat different.

The <template> tag's main purpose is to, as the name applies, store HTML for a later time, and or to be used repeatedly across the document. This tag is useful when using a template engine where the contents are usually never changed but the input may be different.

document.createDocumentFragment is used to create an entire DOM tree in JS without the browser rendering it, while still having the ability to use the DOM API with it. This useful when dynamically generating HTML by leveraging the DOM API, and to later inject the results in the actual document's DOM.

More: Template Tag and DocumentFragment

like image 143
dotconnor Avatar answered Nov 04 '22 08:11

dotconnor