TweetGet Multiple Computed Styles FAST with the curStyles jQuery Plugin
Do you use jQuery’s css or curCSS functions to get multiple styles on the same element? Don’t you know this is slow? The JavaScriptMVC extracted curStyles plugin boosts performance when reading multiple computed styles on a single element.
Download
jquery.curstyles.js (minified 0.9kb) [works with any version of jQuery]
Features
- Gets multiple computed style values on a single element.
- Takes hyphenated (padding-left) or camelCase (paddingLeft) names.
- Performs faster than curCSS.
Demo
See how to make a 2-3X faster jQuery.fn.height plugin in the curStyles demo.
Documentation
JavaScriptMVC’s curStyles docs.
Use
Call curStyles on your jQuery element to get a JavaScript object of style-value pairs. For example:
$('#foo').curStyles('paddingTop','marginTop')
might return something like:
{
paddingTop: '2px',
marginTop: '12px'
}
The values returned are the element’s computed style values.
Computed Style Values
An element’s computed style value is the measurable value (typically in px) of all the styles applied on the element. In IE, these values are calculated from properties on the currentStyle property of an element. In all other (standard) browsers, these values are found using getComputedStyle.
A Faster jQuery.fn.height
The following makes a jQuery.fn.height plugin and is shown in the demo.
$.fn.fastHeight = function(){
//start with the offsetHeight
var sum = this[0] && this[0].offsetHeight;
// subtract out the current values
$.each(
this.curStyles(
"borderTopWidth",
"borderBottomWidth",
"paddingTop",
"paddingBottom"),
function(name, val){
sum -= parseInt(val) || 0;
});
return sum;
}
Conclusions
This plugin is very useful for optimizing performance critical paths. If you need to get only a handful of computed properties from an element over and over again, you can typically double its speed by using curStyles.