Oliver Nassar

I can be reached at onassar@gmail.com.

For my open source work, check out github.com/onassar

Device and layout specific JS booting

View more posts

Working on a script that loads different js depending on what type of device (eg. desktop browser, ipad browser, iphone browser) is accessing it, and in which view (landscape vs. portrait). Worked up this little script to help:

// orientation-detection
var landscape = true;
if (typeof window.orientation !== 'undefined') {
    if (window.orientation % 180 === 0) {
        landscape = false;

// device-detection
var device = 'desktop';
if (navigator.userAgent.match(/iPad/i)) {
    device = 'tablet';
} else if (navigator.userAgent.match(/iPhone/i)) {
    device = 'mobile';

// device-specific booting
var path = 'web.js';
if (device !== 'desktop') {
    path = device + '.' + (landscape ? 'landscape' : 'portrait') + '.js';
// here i do the booting; this would change depending on what framework (if any) you're using

An interesting thing I found out was how the iPad records the window.orientation property. It has four possible values. They are, in clockwise order from the conventional position: 0, 90, 180, -90.

I would've expected a fourth value of 270, but it decides to go negative. Maybe this is in a spec somewhere, but it def. surprised me.

Worth noting is that while I'm marking a device as being either a tablet or mobile based solely on their matching of either the iPad or iPhone user agent value, this could (and will) be updated to include other devices (eg. android, galaxy, etc.). I just wasn't able to find a universal way of detecting mobile and tablet's versus desktop browsers, so figured this hack would work for a little while.