<template id="template">
<div>
<p class="font-bold">Hello!</p>
</div>
</template>
<output id="output"></output>
output.replaceChildren();
output.innerHTML += `
<div>
<p class="font-bold">Hello!</p>
</div>`;
const div = document.createElement('div');
const p = document.createElement('p');
p.classList.add('font-bold');
p.textContent = 'Hello!';
div.appendChild(p);
output.appendChild(div);
output.appendChild(template.content.cloneNode(true));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
innerHTML | |
Imperative DOM | |
<template> |
Test name | Executions per second |
---|---|
innerHTML | 83.1 Ops/sec |
Imperative DOM | 221364.9 Ops/sec |
<template> | 152713.6 Ops/sec |
I'll break down the provided benchmark definition and test cases, explaining what's being tested, the pros and cons of each approach, and other considerations.
Benchmark Definition
The benchmark measures the performance comparison between three approaches:
innerHTML
property.Test Cases
Each test case represents one of the three approaches:
output.innerHTML += `\r\n <div>\r\n <p class="font-bold">Hello!</p>\r\n </div>`;\r\n
This code sets the inner HTML of the output
element to a new string containing a <div>
element with a <p>
element inside.
Pros:
Cons:
const div = document.createElement('div');
const p = document.createElement('p');
p.classList.add('font-bold');
p.textContent = 'Hello!';
div.appendChild(p);
output.appendChild(div);
This code creates two new DOM elements (<div>
and <p>
) and appends them to the output
element.
Pros:
Cons:
output.appendChild(template.content.cloneNode(true));
This code appends the content of a template element to the output
element using the cloneNode()
method.
Pros:
Cons:
Library: Template Elements
The <template>
element is a native HTML element that allows you to define a fragment of HTML content as a separate entity. The content
property of the template
element returns the cloned content, which can be appended to another element. This feature is useful for generating HTML content dynamically and efficiently.
Special JavaScript Feature/Syntax
There are no special JavaScript features or syntax mentioned in this benchmark definition. However, note that template stamping uses a modern JavaScript feature called "template literals" (\r\n <div>\r\n <p class="font-bold">Hello!</p>\r\n </div>
), which is supported by most modern browsers.
Alternatives
Other alternatives for generating HTML content include:
insertAdjacentHTML()
or appendChild()
to append elements to the DOM.Keep in mind that each approach has its own trade-offs in terms of performance, complexity, and compatibility with different browsers and environments.