Stefan Petre

Alter CSS rules to speedup setting styles

When I started to develop on my blog I faced an issue on Firefox. When animating DOMElements with 'overflow' CSS property set to 'auto' inside another DOMElement with 'overflow' set to hidden, Firefox creates all sorts of artifacts. To fix this, all animated DOMElements must have 'overflow' set to 'hidden' and return to 'auto' when animation ends. Since I'm using jQuery this can be done very easy.

$('div.item').css('overflow', 'hidden');

This is OK, but, in time, when the blog post number increase, this query will get slower and slower and it may affect the animation.

Then I got an idea: What if I alter the CSS rules present in document? This may be very quick since the script will not cycle through all elements to set individual style, but just change the CSS rule itself and automatically the elements will inherit that change. So there you have, a small function to alter the CSS rules:


$.alterCSSRule = function(ruleName, props) {
var styleSheet,
cssRule,
selectorStr;
if (document.styleSheets) {
for (var i=0; i<document.styleSheets.length; i++) {
styleSheet = document.styleSheets[i];
for (var
k=0,
lng = styleSheet.cssRules ?
styleSheet.cssRules.length :
styleSheet.rules.length;
k <lng;
k++) {
cssRule = styleSheet.cssRules ?
styleSheet.cssRules[k] :
styleSheet.rules[k];
selectorStr = cssRule.selectorText + '';
if (selectorStr == ruleName) {
for (var j in props) {
cssRule.style[j] = props[j];
}
}
}
}
}
};

And to use this new function ...

$.alterCSSRule.('div.item',{overflow: 'hidden'});

And it is quick, just check this speed test  altercssspeed.html . For this to work properly you must be aware of that inline styles will not be overwritten.

I tested this function so far on:

Comentarii (0)

Nu sunt inca comentarii.

Adauga comentariu
* Campurile marcate sunt obligatorii
eyecon.ro is using cookies to personalise content and ads, to provide social media features and to analyse our traffic. I also share information about your use of my site with my social media, advertising and analytics partners.See details

By continuing to browse the site you are agreeing to my use of cookies. ✔ Continue