const targetElem = document.createElement( 'DIV' );
targetElem.id = 'target';
targetElem.innerHTML = `
<div>
<span>Child 1</span>
</div>
<div>
<span>Child 2</span>
</div>
<div>
<span>Child 3</span>
</div>
`;
document.body.appendChild( targetElem );
const range = new Range();
const frag = range.createContextualFragment("<h1>Some header</h1>")
document.getElementById("target").appendChild(frag);
document.getElementById("target").insertAdjacentHTML("afterbegin", "<h1>Some content</h1>")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
using range | |
using insertAdjacentHTML |
Test name | Executions per second |
---|---|
using range | 6769.2 Ops/sec |
using insertAdjacentHTML | 6662.4 Ops/sec |
Let's break down the provided benchmark definition and test cases to understand what's being tested.
Benchmark Definition
The benchmark is comparing two methods for inserting HTML content into an element:
insertAdjacentHtml
: This method inserts the specified HTML at a given position relative to the element. The available positions are:beforebegin
(default): inserts before the beginning of the elementafterbegin
: inserts after the beginning of the elementbeforeend
: inserts before the end of the elementafterend
: inserts after the end of the elementcreateContextualFragment
: This method creates a new fragment containing the specified HTML and appends it to an existing range.Script Preparation Code
The script preparation code creates a <div>
element with an ID of "target", sets its innerHTML, and appends it to the document body.
Html Preparation Code
There is no HTML preparation code provided, so the test will likely use the default HTML provided in the Script Preparation Code.
Individual Test Cases
The two test cases are:
**: This test case uses the
createContextualFragmentmethod to create a new fragment containing an
**: This test case uses the
insertAdjacentHtmlmethod to insert an
Options Compared
The two methods being compared are:
createContextualFragment
insertAdjacentHtml
Pros and Cons
Here's a brief overview of the pros and cons of each approach:
createContextualFragment
Pros:
Cons:
insertAdjacentHtml
Pros:
Cons:
Libraries Used
None are explicitly mentioned in this benchmark definition.
Special JS Features or Syntax
This benchmark does not use any special JavaScript features or syntax. It only uses standard JavaScript constructs and methods.
Other Alternatives
If you're looking for alternative methods to insert HTML content into an element, some other options include:
innerHTML
(although this is generally considered less efficient than the two methods being compared in this benchmark).append()
method.Keep in mind that the best approach will depend on your specific use case and requirements.