<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style>
#wrap1 {
width:300px;
margin:10px;
padding:10px;
border:10px solid black;
}
#wrap2 {
margin:10px;
padding:10px;
border:10px solid red;
}
#myDiv {
margin:10px;
padding:10px;
border:10px solid blue;
}
</style>
<div id="wrap1">
<div id="wrap2">
<div id="myDiv">
Test
</div>
</div>
</div>
var myDiv = document.getElementById('myDiv');
var $myDiv = $(myDiv);
var getStyle2;
// getComputedStyle isn't compatible with all older browsers (notably IE),
// so this is a wrapper function that works with those browsers.
// From http://www.quirksmode.org/dom/getstyles.html
function getStyle(el, styleProp) {
if (el.currentStyle)
var y = el.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
return y;
}
if (window.getComputedStyle) {
getStyle2 = window.getComputedStyle;
} else {
getStyle2 = function(el) {
return el.currentStyle;
}
}
var npaddingTop = $myDiv.css('padding-top');
var npaddingTop = getComputedStyle(myDiv).paddingTop;
var npaddingTop = getStyle(myDiv, 'paddingTop');
var npaddingTop = getStyle2(myDiv)['paddingTop'];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
jQuery.css | |
getComputedStyle() | |
getStyle() | |
getStyle2() |
Test name | Executions per second |
---|---|
jQuery.css | 764204.7 Ops/sec |
getComputedStyle() | 1654128.6 Ops/sec |
getStyle() | 5409972.5 Ops/sec |
getStyle2() | 1676912.2 Ops/sec |
The provided JSON represents a JavaScript microbenchmark test case, specifically designed to compare the performance of three approaches for retrieving CSS styles in an HTML document: jQuery's .css()
method, getComputedStyle
(a DOM API), and a custom wrapper function (getStyle
) that mimics the behavior of getComputedStyle
.
Options Compared:
.css()
method to retrieve the value of a CSS property.getComputedStyle
DOM API to retrieve the value of a CSS property for an element.getComputedStyle
. It checks if window.getComputedStyle
is available and falls back to using the currentStyle
property on the element.Pros and Cons:
getComputedStyle
without relying on a specific library or API.Cons:
Library:
.css()
method is designed to be lightweight and efficient.Special JS Features/Syntax:
None mentioned in this specific benchmark test case. However, it's worth noting that getComputedStyle
relies on the DOM API, which uses JavaScript to interact with the browser's CSS engine. The custom getStyle
wrapper function mirrors this behavior, using a similar approach to retrieve CSS properties.
Other Alternatives:
If you need more advanced or specialized features, such as:
Keep in mind that the performance benefits of each approach may vary depending on your specific use case, browser, and hardware.