Quick Coding Tip: Body Class for iOS Devices (Cache Friendly!)

At 10up, responsive design is a hot request. In fact, over the course of the last year, we’ve seen this type of work evolve from relative indifference – when pitched – to a common client expectation.

It often makes sense to release a new “desktop” experience before rolling CSS3 media queries or other responsive techniques. Furthermore, you might invest in contextual layout for phone screens, but leave the “desktop” experience for tablet devices. While devices like an iPad or iPhone do a great job of rendering any web page (this was the original selling point!), there are cases where the layout calls for subtle changes. In one case, we needed to hide buttons that spawned unsupported technologies (e.g. Flash) on iOS devices. We also had to deal with a subtle but ugly iOS Safari quirk involving large background images.

It’s easy enough to write server side code (e.g. PHP) that changes the output based on the browser’s user agent, but if you need to work with page caching, server side code based on visitor specific properties isn’t an option.

The following simple JavaScript code snippet will add a “browser-ios” class to your body tag that will allow you to easily tweak elements with basic CSS, and without any server side concerns like page caching.

This simple snippet does depend on jQuery. You can accomplish this without jQuery, but it involves either considerably more lines of code or using JavaScript’s document “onload” event, which would result in the class not being added till fairly late in the page loading process.

if( navigator.userAgent.match(/iP(hone|od|ad)/i) ) {
     jQuery('body').addClass('browser-ios');
}

You can place this anywhere after the opening “body” tag in your HTML. I’d recommend right after that tag.

  1. For situations where no jQuery is available:

    if (navigator.userAgent.match(/iP(hone|od|ad)/i))
    document.body.className += ‘ browser-ios’;

Leave a Comment

Finely crafted websites & tools that make the web better.