I was looking for a quick way to extract my Internet Explorer styles into their own CSS file so it could be conditionally loaded for older versions of the browser and not clutter up my main stylesheet, so I took the opportunity to create my first Grunt plugin to achieve the task.
I tend to use old Paul Irish trick of using conditional comments to add extra classes such
.ie8 to the HTML element depending on which version of Explorer is being used1. This means I can prefix any workarounds for those browsers with a class and not have them interfere with the rest of the styles.
grunt-split-styles allows you to extract rulesets from a CSS file based on the selector and move them over to a new file. It uses the excellent PostCSS post-processing library to do all the hard work of manipulating the CSS.
You can install via npm:
npm install grunt-split-styles --save-dev
The plugin allows me to add this to my
load in the plugin with…
and then run
Which should give me a separate file (
style-ie.css) with just those selectors with the .ie[n] prefix included and a
styles.css file without any extra IE-ness in the way.
Why? Why not!
Now, I have to admit, this was partly an excuse to play with making a Grunt plugin and using PostCSS rather than an meeting an urgent need. The case for having a separate stylesheet for old IE users along with its extra HTTP request (and probably parsing / paint issues) is not so strong that I will need this on every project I do.
That said, I hope by making it flexible (you can extract any selector or media query that you can build a regular expression for) that I may find more uses for it in larger projects beyond its original scope. Some possibilities include:
- Use Modernizr’s feature-detect classes to only load CSS with data URIs when they are available in the browser.
- Collect particularly heavy styles relating to a lesser-used section of a site (assuming something like
- Use the
mediaPattern option to create a widescreen specific stylesheet.
Perhaps the most important lesson was that Grunt plugins are pretty simple and enjoyable to get started with so I hope to make some more in the future to improve my workflow.
Yours for the taking
The plugin, along with instructions is up on GitHub so do try it out and do reach out to me if you find it useful.