First the techniques for tracking when media queries change / initial state:
- matchMedia – this checks css on the page for media queries and returns a list of them. (see https://developer.mozilla.org/en/DOM/window.matchMedia for more info). Great idea, but the browser penetration for it is not really up to scratch for production (here at Cru Digital we still support IE7+ for production – believe me I wish we didn’t have to, but even IE8 is a NIGHTMARE)
Once a decision has been made on which technique to use, then it is just a case of either choosing the right library that works for your project or rolling your own. The other thing to consider is how you like to be “told” that a media query has been fired (possibly including when entering and exiting a specific media query) – generally there are two ways that this occurs – registering callbacks & having events fired. My personal preference (coming from an MVC programming background) is via events – this makes for cleaner / leaner code and makes sure you don’t have references all over your code base to various other parts of your code base (enabling better garbage collection for non-trivial applications). The final consideration to make is to ensure your library of choice tracks what media query you are currently in, which helps when you want to just do a quick check for the current state of the browser media queries.
Personally I can’t wait for matchMedia to be more possible to use (ie: browser penetration – come on Chrome & Firefox) and as yet I have not had the chance to use Paul Irish’s matchMedia polyfill, but for the mean time we have used the Conditional CSS technique from Springload (nice one guys!) in a production site (hogsbreath.com.au) and it worked quite well – at least until we got to testing in IE7, IE8 & Android which all don’t have the best support for the :after pseudo element – so there were a couple of little changes to it to make it work for us, but that would not be a problem with the current version of the library.
- matchMedia.js – a matchMedia polyfill from who else, but Paul Irish
- Smart resize – reduce the number of events that occur when browser resizing (increase performance of code)
- MDN article on matchMedia
- MDN aticle on using matchMedia in code
- Can I Use page for matchMedia support
Whatever you all use – make sure it works for you in your project and above all test, test, test! This is an exciting time to be developing on the web – so much cool new stuff and so much to learn!