<html lang="en">
<head>
</head>
<body>
<div id="foo"></div>
</body>
</html>
const pageBody = document.querySelector('html');
const pageBody = document.documentElement;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelector | |
Direct access |
Test name | Executions per second |
---|---|
querySelector | 10085565.0 Ops/sec |
Direct access | 13648050.0 Ops/sec |
The benchmark provided is designed to compare the performance of two different methods of accessing the root HTML element of a document in a web browser using JavaScript:
document.documentElement
querySelector
with document.querySelector("html")
Direct Access:
const pageBody = document.documentElement;
documentElement
is a predefined reference that returns the <html>
element of the document.Query Selector:
const pageBody = document.querySelector('html');
querySelector
function, which is a more versatile and general-purpose method for selecting elements based on CSS selectors. In this case, it's specifically selecting the <html>
element.The benchmark results measured in ExecutionsPerSecond
are as follows:
This indicates that the direct access method is more than 35% faster than the querySelector method in this particular execution context on the given hardware and browser platform.
document.documentElement
)querySelector
(document.querySelector('html')
)When performance is a critical factor, such as in high-frequency operations (like animations or when manipulating the DOM in response to user events), using direct access is advisable. In scenarios where you need more complex queries or want to operate on various selectors dynamically, querySelector
is beneficial despite its performance cost.
Other alternatives to access the root HTML element in JavaScript include:
Using getElementsByTagName
:
const pageBody = document.getElementsByTagName('html')[0];
This approach retrieves a live HTMLCollection of elements with the specified tag name. While it may offer benefits in specific use cases, it's generally less intuitive and can be slower than direct property access.
Using jQuery (if included in the project):
const pageBody = $('html');
While jQuery provides a powerful and flexible interface for DOM manipulation, it also adds significant overhead and dependency, making it generally less preferable for simple tasks compared to vanilla JavaScript.
In summary, developers should choose the method based on their specific use cases—favoring performance in critical paths while leveraging convenience and flexibility when necessary.