A simple JS library that detects mobile devices.
You probably shouldn't use this library unless you absolutely have to. In most cases, good responsive design solves the problem of controlling how to render things across different screen sizes. But there are always edge cases. If you have an edge case, then this library might be for you.
I had very specific requirements for a project when I created this:
- Redirect all iPhones, iPods, Android phones, and seven inch devices to the mobile site.
Yep, at the time, a completely separate site had already been created for mobile devices. So I couldn't depend on media queries, feature detection, graceful degradation, progressive enhancement, or any of the cool techniques for selectively displaying things. I had to find a way to redirect visitors on certain devices to the mobile site.
I couldn't do detection on the back-end, because the entire site was generated as HTML, and then cached and served by a CDN, so I had to do the detection client-side.
So I resorted to User-Agent (UA) sniffing.
I tried to keep the script small (currently ~1.4k bytes, minified) and simple, because it would need to execute in the
<head>, which is generally a bad idea, since JS blocks the downloading and rendering of all assets while it parses and executes. In the case of mobile redirection, I don't mind so much, because I want to start the redirect as soon as possible, before the device has a chance to start downloading and rendering other stuff. For non-mobile platforms, the script should execute fast, so the browser can quickly get back to downloading and rendering.
The following properties of the global
isMobile object will either be
isMobile.apple.device(any mobile Apple device)
isMobile.android.device(any mobile Android device)
isMobile.amazon.device(any mobile Amazon Silk device)
isMobile.windows.device(any mobile Windows device)
trueif the device is one of the following 7" devices:
isMobile.other.device(any "Other" device)
isMobile.any- any device matched
isMobile.phone- any device in the 'phone' groups above
isMobile.tablet- any device in the 'tablet' groups above
I include the minified version of the script, inline, and at the top of the
<head>. Cellular connections tend to suck, so it would be wasteful overhead to open another connection, just to download ~1.8kb of JS:
<!-- imagine lots of html and content -->
npm install ismobilejs
var isMobile = require('ismobilejs');console.log(isMobile(req.headers['user-agent']).any);