Clean conditional loading

It's December. That means it's time for the geek advent calendars to get revved up again:




PHP Advent 2011,
Adfont Calendar 2011 and
24 Ways 2011.


For every day until Christmas eve, you can find a new tasty geek treat on each of those sites.



Today's treat on 24 Ways is a little something I penned called Conditional Loading for Responsive Designs. It expands on the technique I'm using on Huffduffer to conditionally load inessential content into a sidebar with Ajax when the layout is wide enough to accommodate it:






In that example, the Ajax only kicks in if the viewport is wider than 640 pixels. Assuming I've got a media query that also kicks in at 640 pixels, everything's hunky-dory.



But …it doesn't feel very DRY to have that 640 pixel breakpoint repeated in two places: once in the CSS and once in the JavaScript. It feels even ickier if I'm using ems for my media query breakpoints (as I often do) while using pixels in JavaScript.



At my recent responsive enhancement workshop in Düsseldorf, Andreas Nebiker pointed out an elegant solution: instead of testing for the viewport width in JavaScript, why not check for a style change that would have been executed within a media query instead?



So, say for example I've got some CSS like this:



@media screen and (min-width: 640px) {
[role="complementary"] {
width: 30%;
float: right;
}
}


Then in my JavaScript I could test to see if that element has the wide-screen layout or not:



var sidebar = document.querySelector('[role="complementary"]'),
floating = window.getComputedStyle(sidebar,null).getPropertyValue('float');
if (floating == 'right') {
// Use Ajax to retrieve content here.
}


Or something like that. The breakpoint is only specified once so if I ever change it from 640 pixels to something else (like 40 ems) then I only have to make that change in one place. Feel free to grab the example and play around with it.



By the way, you'll notice that in the original 24 Ways article and also in this updated example, I'm only testing the layout on page load; not on page resize. It would be fairly easy to add in an onResize test as well but I'm increasingly coming to the conclusion that—apart from the legitimate use case of orientation change on tablets—the only people resizing their browser windows after the page loads are web designers testing responsive designs. Still, it would be nice to see some more data on this hypothesis.





Tagged with
responsive
javascript
css
conditional
loading
ajax
24ways

 •  0 comments  •  flag
Share on Twitter
Published on December 02, 2011 07:11
No comments have been added yet.


Jeremy Keith's Blog

Jeremy Keith
Jeremy Keith isn't a Goodreads Author (yet), but they do have a blog, so here are some recent posts imported from their feed.
Follow Jeremy Keith's blog with rss.