jQuery Mobile Best Practices - a one year retrospective

jQuery Mobile is very easy to use. For anyone who knows jQuery, it's also very easy to manipulate. But with great power comes great responsibility. I've been working with JQM in a corporate and small business settings since it was in alpha 2 and these are some of the lessons I've learned. If you take these to heart, hopefully I can save you some of the same headaches.  Much of this is true about going mobile for anyone. jQuery Mobile was simply my chosen platform.  I stand by that choice.

Author's Note:

Creating Mobile Apps with jQuery Mobile by Shane GliserPackt Publishing recruited me to write a book on jQuery Mobile!

Once you've read this article and found it useful, you should order my book. It's full of real world examples that span several industries and technologies using jQuery Mobile. The eBook editions are cheap and obviously, you know where to come if you have follow up questions ;-)

Check out Creating Mobile Apps with jQuery Mobile

This Article's Table of Contents:

Things I shouldn't have to say but you should read anyway...

The meat of the post...

  1. Minify, combine, and compress (the 25k HTML cap, 1MB for CSS/JS)
  2. Always use a global configuration script on every page
  3. Phone numbers, maps, and emails
  4. Validate using jQuery Validate
  5. Use the ThemeRoller
  6. Use radio button groups instead of select menus
  7. Add Google Analytics
  8. Use the right meta viewport tags
  9. Determine which navigation style to use
  10. How to deal with tablets
  11. Detecting and redirecting to mobile
  12. Provide a full site link
  13. Hosting your mobile site
  14. Content vs. functionality
  15. Don't start with the code
  16. Follow the right people
  17. Ask Questions


#0a - Go through ALL the docs and demos.

I will not be going through the docs and demos of JQM. They are well exampled and more than sufficient to train you up in the basics. Once you have a good grasp on what the framework is capable of, you can then start thinking about your projects. It's really not complicated. 

#0b - Each page should be fully self contained and capable of standing alone

I cannot stress this point enough, you should be structuring every page so that it can stand alone if called directly (because at some point, it will be, I guarantee it). This means that each page should contain the global custom css, global scripts, headers, footers, etc. Do not try to shortcut this or it will bite you in the app!

#0c - At least once, turn off the javascript

It's going to happen to you at one point or another. One of your users will be on a corporate controlled smartphone that has had it's JavaScript turned off until a security patch can be provided. Through no fault of their own, the user will be crippled. However, if you've done your job well, they'll still be able to function, even if it is as ugly as a dumb-phone. Consider the escelator. When it breaks, it doesn't become useless. It becomes stairs. Similarly, JQM works through progressive enhancement to take what is a well structured page and turn it into something beautiful for those who can handle it. A well designed JQM page will work for everyone, even if JavaScript is turned off.

#0d - Never trust the client

From one device to the next, you have no idea what's going to work and what isn't. Its worse than the wild-wild-west out there. If you do not validate and sanitize the inputs on the server then you are opening yourself up for all manner of attacks: cross site scripting, SQL injection, etc.

#1 - Minify, combine, and compress (the 25k HTML cap, 1MB for CSS/JS)

  • Reducing the number of HTTP requests required to render the page is the best thing you can do.
  • Combine and minify your css and javascript files as much as possible
  • Try to keep individual HTML pages under 25k (uncompressed) to avoid the 25k soft cap on the cache External CSS and JS files should be less than 1MB.
  • Use tools like YUI Compressor to minify your scirpts.
  • Consider micro caching your content and assets. Maybe for a day, perhaps an hour, even one minute can cause ISP's servers to cache your content and thus speed up experiences such that the request never even hops all the way back to your server.

#2 - Always use a global configuration script on every page

	<script src="jquery.js"></script>  
	<script src="custom-scripting.js"></script>  
	<script src="jquery-mobile.js"></script>

Not only does this allow you to override defaults (which you'll inevitably want to do at some point) but any script that you could use on more than one page should probably be placed here. Read more about global configuration scripts here.

#3 - Phone numbers, maps, and emails

View of RioSalonKC.com's mobile site

People who engage on mobile are 9x more likely to take the next step. Why not make it easy? This is particularly important for any business where getting people on the line or to a physical location is critical for your business. At this point, developers tend to nerd out a little bit so I'll throw out a word of caution: DO NOT EMBED MAPS INTO YOUR MOBILE SITE. Was I unclear there? I hope not, because the user experience is abysmal. For the developer, it's a nerdvana moment, "look what I did!" For anyone using it, it's a true WTF experience that can drive your customers away.

Here's the bottom line with maps in mobile, the native maps programs do it better than you ever will. They're faster, more reliable, touch optimized, and can instantly give directions from their current location. On iOS and Android, the browser is made to intercept standard links to Google Maps and pull up the locations in their native map applications. That will take care of better than 80% of the market who actually surfs the web with their phone. The remaining people will be given a page from Google Maps who already optimizes their mobile experience quite well if you just link to them.

For mail, it's a given that every single smartphone out here has an email client on the device and, once again, working with it will be a far superior user experience than any web form you can put together. Just link to the email address you want and let their native client do the rest.

Here's how to link to phones, maps, and emails:

href="tel:+1[your telephone number here (numbers only)]"
href="[standard link to google maps here]"
href="mailto:[your email address]"

#4 - Validate using jQuery Validate

Wait, didn't I just tell you not to trust the clinet? OK, fine. Trust but verify. Watch for a future post on this topic in depth. You can easily tie in jQuery Validate on every page by including it in the head and adding it to every form dynamically in the global config script. It's only 22k so the first hit will cache it for all subsequent hits.

	<script src="jquery.js"></script>
	<script src="jquery.validate.min.js"></script>
	<script src="custom-scripting.js"></script>
	<script src="jquery-mobile.js"></script>

Inside your global configuration script you can check for any form that you might want to validate upon the page's initialization. In the example below I'm looking for any form that I've tagged with the class of "validateMe."

$("div").on("pageinit", function(){
        //Any form that might need validation
        if($("form.validateMe").length > 0){

#5 - Use the ThemeRoller

(in an old man's voice) Back in my day, we didn't have a theme roller! We were overriding and custom crafting themes by hand and we liked it! In the end, you'll probably still have to do a little customization, but, you can save yourself a lot of time by using http://jquerymobile.com/themeroller/

#6 - Use radio button groups instead of select menus

Using Radio buttons groups instead of select menus has several advantages

  1. Radios are not limited in the the amount of content you can fit in the label.
  2. Radio buttons promote consistency across platforms because they avoid the native select interface.
  3. Radio buttons allow the user to instantly see options without having to take an action first.
  4. With only a little tweaking of css and manual class additions, you can give the labels the same beautiful text treatments as listviews.

Add this to your custom CSS file:

.ui-checkbox .ui-li-heading, 
.ui-radio .ui-li-heading{
.ui-checkbox .ui-li-desc, 
.ui-radio .ui-li-desc{

Then you can make more helpful radios using code like the next block. Please note that I have manually added the classes of "ui-li-heading" and "ui-li-desc" to the h3 and p tags to give them the same look and feel as the listviews.

<fieldset data-role="controlgroup"> 
    <input type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked" />
    <label for="radio-choice-1">
        <h3 class="ui-li-heading">jQuery Mobile</h3>
        <p class="ui-li-desc">Easy and great for all project from smartphones to dumbphones</p>
    <input type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2"  />       	
    <label for="radio-choice-2">
        <h3 class="ui-li-heading">Sencha Touch</h3>
        <p class="ui-li-desc">Great for complex apps but a higher learning curve</p>
    <input type="radio" name="radio-choice-1" id="radio-choice-3" value="choice-3"  />       	
    <label for="radio-choice-3">
        <h3 class="ui-li-heading">jQTouch</h3>
        <p class="ui-li-desc">Simple, lightweight, but focused on webkit</p>

#7 - Add Google Analytics

analytics snap shot

If you're not using some sort of an analytics package then you're flying blind. It's really not that difficult and can give you very interesting insights like:

  • Are there certain days that I get more traffic than others?
  • How are most people finding me?
  • What pieces of content do people like the most?
  • What technologies are my visitors using?
  • At what point in the process are people dropping off?

The most important thing to remember about analytics is that the absolute numbers are not important. Watch the trends!

Analytics tracking in jquery mobile is a little bit different then on a normal page-by-page site. You no longer track pages views based off of real page views, instead you have to trigger them on the "pageshow" event. Also, the URL that shows up in the address bar might not actually be the real file that was pulled from the server. What you'll actually want to track is the attribute "data-url" on the active page.

    var _gaq = _gaq || [];

	$(document).ready(function(e) {
		(function() {
		  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + 
		  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

	$('[data-role=page]').live('pageshow', function (event, ui) {
		try {
			_gaq.push(['_setAccount', 'YOUR_ANALYTICS_ID_GOES_HERE']);
			if ($.mobile.activePage.attr("data-url")) {
				_gaq.push(['_trackPageview', $.mobile.activePage.attr("data-url")]);
			} else {
		} catch(err) {}

#8 - Use the right meta tag

The docs and examples on the jquerymobile site have a meta viewport tag that, if you phone is rotated, will cause it to scale is wierd ways.  If you used this meta viewport tag instead, it will solve all your problems.  The only problem with this is that it disables zooming.  The new 1.1.0 edition of jQuery Mobile attempts to solve this with a javascript trick.  However, the question that should be asked is... should it be solved.  From a usability standpoint, taking away choices from the users is usually not a good thing.  However, in this case, you ensuring a uniform experience across devices and preventing people from accidentally zooming.

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">

#9 - Determine which navigation style to use

There are a lot of ways that you could make a menu for your mobile site.  The three main ways are,

  • The homepage is the main menu
  • Global menu at the bottom that is linked to with a Menu button at the top
  • Global menu as a seperate page that is launched as a dialog

Check out one of my earlier posts, three ways of handling global navigation, for more details on this topic and why you might choose each option.

#10 - How to deal with tablets

A long time ago in a galaxy far far away, Mark Zuckerberg once proclaimed that "iPad's not mobile...it's a computer."  Oh really?  Certainly, you could take this approach but what about smaller tablets?  How about the Samsung Galaxy Note? Nook?  The real question is not, "is it mobile,"  the question is, "what is the interface?"  Certainly, all these devices use a touch interface and in the end, that's really what this is all about.  

On the desktop, we have fine control over the cursor using a mouse.  On this new generation of touch driven devices, we only have our fingers and so the interaction points must be larger and better spaced.  The sizes of these tablet-like devices both now and in the future will run the entire spectrum but what they all have in common is a touch interface.  jQuery Mobile is perfectly suited for any touch device and you wont go wrong by using it for any touch enabled device including touch screen desktops.

#11 - Detecting and redirecting to mobile

The first thing to realize is that most people are not going to naturally go to your mobile site.  They'll find you through a search engine or a link they find somewhere.  So, if you want to provide the user with the most seamless experience possible, you're going to have to detect if they are mobile and automatically bounce them to the mobile view.  Of all mobile implementation topics, this is probalby the hardest thing to get right because each method has its advantages based of who you intend to support.

The first question you need to ask yourself is, are you going to let in people who do not have javasript on their device?  If that's the case, then you will have to detect mobile on the server through the request headers (browser sniffing).  The most simple way would be to sniff for the platforms that you wanted to support but that's not very future proof.  A better way would be to use a tool like the WURFL project.  Since it's a community driven database, you're likely going to have far better results and lower on-going maintenance.   

The most future friendly method of detecting mobile would be by detecting device capabilities.  This cobbled together detection script is taken partly from a Responsive News blog post, Modernizr, and a Windows Phone Developer Blog post.  Together, they detect if the browser supports HTML5 capabilities and is reporting that it's a touch screen.  There is also a direct platform sniff in here for the Windows Phone 7+ which does not report itself as responding to touch events.  (Anyone shocked by this?  Anyone??).  It is worth noting here that I am NOT checking the screen size and there is a very good reason.   Most mobile browsers misrepresent their screen sizes.  Beyond that, if the user is on a touch enabled interface, wouldn't it just make sense to use a touch optimized interface?

if( ('querySelector' in document
     && 'localStorage' in window
     && 'addEventListener' in window
     && ('ontouchstart' in window || window.DocumentTouch && document instanceof DocumentTouch)
     || navigator.userAgent.indexOf('IEMobile') > 0){       
        location.replace('YOUR MOBILE SITE');

As you can see, there's not good clean way to do this.  Sadly, this problem is only going to get worse.  My personal recommendation would be to use WURFL.  That way, you can even let in people who do not have JavaScirpt.  So long as you've coded your pages well, like I pointed out in tip 0b, then everything should still work fine. 

#12 - Provide a full site link

The fact that you're using jQuery Mobile means there's a 99.999% chance that you have a seperate mobile site from your full site.  You could, in theory, make your entire website a pure JQM site and I'm sure there are some who have done it and that it turned out pretty cool.  For everyone else, unless you've managed to completely duplicate all capabilites and content on your mobile site, there will inevitably be users who would prefer to view the full site version.  Perhaps if for no other reason than that they know where to look.  The larger your site, the more likely that possibility becomes.

#13 - Hosting your mobile site

Time to defy a convention or two.  Most sites that you see that are mobilized are being hosted on a domain differnet from the main website.  Usually this is "m.mysite.com" or that ill-conceived .mobi TLD.  The problem with this approach is that if the user wants to switch to the full site view but had already authenticated, you could end up making your users have to log in again on the main domain.  These routes into your mobile site are quite common so their still probably wise to use BUT they should only be used as redirects into your main site where your mobile version of the pages are hosted in sub directory like /m.  This allows for seamless switching between views, a single deploy process for all your sites, and removes complications arising from the brower's same origin policy

#14 - Content vs. functionality

Mobile usage falls into 3 basic categores:  

  • I'm bored,
  • I'm socializing or playing
  • I'm trying to accomplish a task

The vast majority of the time, the user is looking for a very quick payoff and will only be interacting with you in short bursts.  Even those who are bored are probably looking for the quick payoff, not becasue they're not willing to kill time, but because they've become very used to quick, relevant success on their devices.  You are going to have to know your audience well.  Part of that is going to mean a laser focus on content and functionality strategies.

Translating/adapting ALL your sites content to mobile makes about as much sense as multiplying a three dollar bill by a bucket of fried chicken.  Unless you're a WebMD or Wikipedia or some other site where content is literally all you have to offer, then what people are coming to your site for, is to get something done and they don't need all that content on your main site getting in the way. An analysis of your analytics package can show you which pieces are driving traffic and which ones are virtually useless.   Be judicious and deliberate in the content that you add to mobile because the more you add, the more navigation is require, the longer it take uses to find/do what they came for. 

This does not mean that people want limited functionality.  In fact, the quickest way to frustrate your user is to not let them do what they came for.  Your functionality strategy should cover as much of the main site's capabilites as possible.  Your user's don't want to have to switch to the full-site-pinch-zoom view to get things done.  

But wait, on one hand I seem to be saying to restrict what you're giving to them (content) and on the other to give them the kitchen sink (functionality).  Yes, yes I am, and there's a very good reason.  Mobile forces you to think in terms of user centered design.  The screen real estate and interaction time window are such that failure to do so will equate to the ultimate failure of your implementation.  If you think about the content of your site, how much of it is actually there to serve the user and how much is there to serve the company's marketing and legal departments, their strategic partners, or just horn tooting.  Now consider how much of your site's functionality is there to directly serve the customer.   Give the customer what they want and make it as easy and expedient as possible.  

#15 - Don't start with the code

PostIt drawing of a mobile pageI am a developer, so, this is really hard for me to say.  jQuery Mobile is very easy and very fast.  Refactoring is also very fast.  However, there is something that happens when you jump right into HTML prototyping. 

  • People who don't know code will assume that you're much closer to a complete product than you actually may be. 
  • People will start to fixate on the minutia of things like spacing and colors and logo size.
  • Due to the sunk cost of your time in the current design, you are less likely to make substative changes from whatever you initially coded.  Refactoring is easier than a do-over.

When you are first getting started, you'll want to familiarize yourself with everything the library can do and what the consituant parts look like.  Do not code.  Instead, this is the time to sketch rough paper prototypes of what you intend to make.  Personally, I love using the 3x5 PostIts.  They pretty well capture the form factor of mobile and can then be placed on a wall to simulate flows in your site/application.  

The great thing about starting with paper based ideation is...

  • You are more willing to simply throwing out a drawing that took less than 30 seconds to create. 
  • Actually sketching by hand uses a differnet part of the brain and unlocks your creative centers.
  • You can come up with 3 completely differnet designs in the time it take to create one HTML page. 
  • Everyone can contribute their ideas of how they think it could work best, not just the graphic designers and coders.
  • You will natrually begin by drawing the most important things first.
  • More attention is paid to the ideas and flows that actually make your site work instead of the miriad details which few would even notice.
  • You will probably end up with a more user centered design since you're drawing what you would want.

For more details on how to do paper based ideation,  check out the book Gamestorming.

#16 - Follow the right people

This framework changes quickly.  Keeping up with it can be interesting, particularly in a corporate environment where everything has to be regression tested before it is let out the door.  However, if you follow the jquery mobile blog and this following list of people, you'll be well set to evaluate if a particular release is worth stepping up to.  Not to mention the brilliant pearls of wisdom that they regularly drop.

#17 - Ask Questions

Chances are, especially if you're just starting down this road, somebody has already done what you're thinking about. There are several very dedicated individuals on StackOverflow who are quick to answer questions about jQuery Mobile.

Beyond that, feel free to ask any questions you like in the comments here and I'll try to either answer them myself or point your to resources that might help.

#18 - Buy my book

Creating Mobile Apps with jQuery Mobile by Shane GliserIf you like what you see in this article, I have squeezed every last drop of my jQuery Mobile knowledge into my upcoming book. It has far more up-to-date examples spanning several industries and many technologies with jQuery Mobile.

You can buy Creating Mobile Apps with jQuery Mobile now from Packt Publishing.

Now, go be brilliant!