Best way to make your site Mobile friendly

how to create mobile friendly websites and why mobile friendly websites are important
GregDeamons Profile Pic
GregDeamons,New Zealand,Professional
Published Date:03-08-2017
Your Website URL(Optional)
Comment
CHAPTER 4 Building Mobile Websites Intelligence is the ability to adapt to change. —Stephen Hawking In this chapter: ■■ From Web to Mobile ■■ Development Aspects of a Mobile Site ■■ The Device-Detector Site ■■ Summary mobile site, much like a native mobile application, is most likely to be consumed by users on the A move: people who are standing up, in a hurry, busy, or waiting in line. Under these conditions, users are probably willing to connect to a site using a tiny device because they really believe that they derive some benefit from the site. The site, therefore, must be direct, concise, and accurate. It is essential that a mobile site should load quickly and allow users to reach all main functionalities in just a few clicks or taps. The user interface should be extremely clear, but also clean and flawless to show the options available at any time, yet still making the act of choosing an option easy. After becoming familiar with the site, users often end up working with it semi-automatically, so even the position of a single button can have an impact on the quality of feedback that you receive. Note that the mobile Human-Computer Interaction (HCI) research field, although new, is very active, and a lot of studies exist about the dos and don’ts of interaction between mobile users and mobile devices and software. Luca Chittaro has a paper that effectively summarizes what mobile HCI means to developers and architects. You can read it here: http://goo.gl/lSG3s. The previous chapter emphasized the importance of accurately selecting the use-cases to i mplement. The number of use-cases, however, should be kept small so that the site doesn’t end up as a shrink-wrapped version of the full site. A pragmatic (and then not necessarily exact) rule is that a mobile site rarely needs more than 20 percent of the features available in the full site. I’d even go further by saying that sometimes, not even the 20 percent of features you take from a parent w ebsite should not necessarily be reimplemented “as is.” You might want to restructure some of these u se-cases and even add new ad hoc use-cases for related scenarios. A mobile site is a brand-new project that can inherit some code and services from an existing site—more often than not, it inherits large shares of the business logic. This chapter covers a number 63of issues and open points that you will want to solve before embarking on building a mobile site. After addressing all these points, building the mobile site is reduced to the work of writing a relatively simple and small website. From Web to Mobile You rarely build a mobile site without also having a full site in place. Most of the time, you build a mobile site to serve mobile users better. In some cases, you start building both full and mobile sites at the same time. Currently, it’s quite unlikely that you build a mobile site as a stand-alone project. Whatever the case may be, however, this section aims at isolating the issues that differentiate a m obile site from a full website. If you’re building a mobile site as a spin-off of an existing website, then the chances are good that you will be able to reuse large portions of the existing application’s back-end code. Those include the data access layer, the domain layer, and possibly a bunch of other distinct components (such as services and workflows) that you may already have in place, which will provide bits and pieces of b usiness logic. If you can replicate some views without too much modification, you may even end up being able to reuse webpages and ASP.NET Model-View-Controller (MVC) controllers—more g enerally, parts of your presentation and application layers. As you move towards the presentation layer, though, the chances of reuse diminish. How would you deal with scripts, images, style sheets, and markup? For images and style sheets, there’s probably an easy answer—you just have to reduce their size. For scripts and markup, the answer is less obvious and likely is influenced by context. Application Structure Before the community of web developers (re)discovered AJAX a few years ago, websites were always built as a navigable collection of distinct pages. Jumping from one page to the next required links and forms. The browser handled each request, which resulted in a full replacement of the current page. AJAX changed the course of things by using the services of a small browser-hosted component—the XmlHttpRequest (XHR) object—through which your script code can play the role of the browser and conduct server requests autonomously. The net effect is that webpages can contain ad hoc script code that use XHR to download data or partial pages. After being downloaded, the content is processed by some other script code and used to update the currently displayed page. AJAX can be used for some specic ( fi perhaps even critical) features, or it can be used extensively throughout the site. When that happens, the site architecture is usually referred to as the Single-Page Interface (SPI) model. the Single-p age Interface Model In brief, the SPI model refers to a web application that behaves more or less like a desktop application—it has a primary user interface (UI) layout that is adjusted and reconfigured via AJAX calls. The page downloads everything it needs from the source site via script-controlled actions. 64 pArt II Mobile Sites The SPI model has been recently formulated as a manifesto. You can read about it here: http://itsnat.sourceforge.net/php/spim/spi_manifesto_en.php. As an early AJAX adopter myself, I’ve always been a fan of the SPI model, but I’ve also always seen it as a vector rather than a concrete pattern to implement. As a result, I have not fully implemented the SPI model in a production site yet, primarily due to lack of confidence, proper facilities, and tools. Moreover, I always found it difficult to sell a 100-percent JavaScript site to a customer—at least, that was true up until two or three years ago. Today, the situation is different. The SPI manifesto dates back to the summer of 2011. With that said, I’m not completely sure that a SPI model is appropriate for just any mobile site. An SPI model requires a lot of JavaScript, partly written by you and for the most part imported from external libraries. You likely need quite a few of these libraries to provide for generic UI manipulation, templates, and data binding. Some of these libraries are based on jQuery and jQuery Mobile. These two libraries alone total some 200 KB (uncompressed) of script and style sheets. Important In a production site, you typically apply minification and GZIP compression to script and other resources, thus reducing significantly the size of the download. Minification is the process of removing unnecessary characters from source code without breaking any functionality. Applied to script files, minification also adds a (thin) layer of obfuscation to your code, making it much harder for humans to read. GZIP is, instead, a popular compression format. Once properly minified and gzipped for a production site, the jQuery library is 31 KB and a bit less for jQuery Mobile. In addition to script, SPI requires helpers for data binding and UI refresh, which adds a few more tens of kilobytes. Popular libraries in this segment include JsRender, JsViews, Knockout, and Upshot. In summary, the size of the JavaScript assets that a client will need to download can consume a few hundred kilobytes, which can become a problem. Once downloaded, of course, the browsers will cache the scripts; they don’t download the code over and over again. But the browser needs to do a lot of work to render SPI pages—work that goes far beyond simply requesting and rendering m arkups. The more advanced the device browser is, the more the SPI model becomes affordable (from a resource standpoint) for mobile sites. Personally, I wouldn’t adopt the SPI model without first performing deep analysis of the context. The main challenges with an SPI implementation can be summarized as follows: ■■ In case of intermittent connectivity, it’s difficult to figure out whether the problem is with the application or the network. This may be frustrating. Not that this same problem doesn’t exist for other models (i.e., the full-page refresh model), but at least tiny, non-SPI pages download well, even with limited bandwidth. Moreover, with no connectivity at all, you immediately grasp the nature of the problem—when nothing shows up, the problem is not the application. ■■ Many sites require users to log on before they will serve content. If the users’ session expires, the full-page refresh model redirects them to the logon page at the first successive access. The CHAPTER 4 Building Mobile Websites 65problem is both manifest and easily resolved. With an SPI site, although user authentication is also AJAX-based, it may take hours before you figure out the root cause of the misbehavior you’re observing. In SPI, user authentication requires due attention and effective client and server-side implementation to work smoothly. So let’s explore some other available options. Note ASP.NET MVC 4 ships with a new project template that promotes the use of the SPI model. The template uses Knockout and Upshot. Full page refresh At the extreme opposite of SPI lies the classic Full Page Refresh (FPR) model. FPR is how the web worked for years: the browser makes a request for a new page, the web server returns the new page, and the browser replaces the current page with the new rendered content. This process occurs r epeatedly for each user action. AJAX (on which SPI is heavily based) made the classic FPR web experience much less compelling, and it also made it more natural for users to expect that only fragments of the current page would be updated as the result of a given action. In a desktop scenario, the FPR model is cumbersome, so more and more large sites are progressively adding AJAX-based capabilities. However, the significant impact that FPR has had on desktop sites (which have large displays and numerous auxiliary resources for downloading, caching, and refreshing content), is less so on mobile sites because mobile pages are considerably smaller and lighter to begin with. Still, loading several small pages may still be less engaging than updating bits and pieces of the currently displayed page. Updating the current page may still be slow over a slow connection, but at least it doesn’t have a dramatic impact on the user experience. partial page r efresh Some middle ground between SPI and FPR can be found in the partial rendering that both ASP.NET Web Forms and ASP.NET MVC support. In terms of traffic, partial page refresh (PPR) falls between the two extremes—it is not as efficient as SPI, but it’s not as poor a user experience as FPR. The idea is that the browser places a request as usual, but that request is captured at the script level—via embedded script—and silently transformed into an AJAX request. On the server side, the web server handles requests as if they were regular full page requests, but the response is packaged as an HTML fragment. The data being transferred is a mix of data and markup—just the delta between the markup of the current page and the requested new page. The benefit of the PPR model is that it offers many of the benefits of AJAX without the cost of having to learn new programming features. In ASP.NET Web Forms, PPR happens relatively a utomatically through the UpdatePanel control; in ASP.NET MVC, it occurs through the Ajax.BeginForm HTML helper. 66 pArt II Mobile Sites In a nutshell, using PPR means that an FPR approach won’t require special skills on the development side. In contrast, an SPI model may represent a complete paradigm shift for many de velopers. PPR represents some middle ground. Context Is King Which of the previous options is preferable? There’s no obvious and clear answer. If you’re d etermined to find just one answer, then the best approach depends strictly on the context and the knowledge that you have about the devices that are going to access your site. If smartphone traffic is p redominant, you definitely can opt for SPI. But if you’re interested in reaching the widest possible audience, then you probably should opt for FPR. The point, though, is that there’s probably no ideal solution that works in all cases. Mobile devices are so different that you really should consider partitioning your audience into a few distinct classes of devices and arrange a different solution for each. That could mean serving plain HTML pages to older browsers while implementing a nicer SPI solution for smartphones. Note In general, you always should consider AJAX seriously because it reduces the amount of network traffic. Extensive use of AJAX, however, actually may raise the number of Hypertext Transfer Protocol (HTTP) requests. In a mobile scenario, an HTTP request is more expensive than in a desktop scenario because connections are slower, limited in number (reduced parallelism in download), and also sometimes processed in a more convoluted way, especially if the connection doesn’t happen over a WiFi network. Amount of JavaScript The amount of JavaScript that you might want to use for the pages of your mobile site is another huge point. Processing JavaScript is crucial to minimize web traffic; on the other hand, it also affects performance. Like it or not, mobile devices (even high-end smartphones) are not as powerful as laptops. Among other things, this means that a mobile device may not be able to tolerate effectively the same amount of JavaScript that you could employ in a full-fledged website. In this context, “not able to tolerate” just means consuming more battery power even if the perceived page performance is acceptable. More Info The consumption of battery power tends to increase with the number of HTTP requests. Subsequently, a JavaScript-intensive page is critical from the resource management perspective. Here’s a reference and some numbers: http://goo.gl/EKcyj. Other excellent resources for making sense of the amount of JavaScript and its performance are Steve Souders’s blog (http://stevesouders.com) and http://goo.gl/jyhV. CHAPTER 4 Building Mobile Websites 67t he jQuery Family of Libraries Today, the jQuery library is a must for nearly any website. I’m personally dreaming of the day when jQuery will be native to browsers and be integrated into every browser’s JavaScript engine. Until that day comes (if ever), jQuery must be linked and downloaded if you plan to use it. Note that jQuery is required even if you plan to use only jQuery Mobile, which offers a variety of ready-made components for scaffolding a mobile site. Plug-ins for jQuery Mobile can put a “skin” on your mobile site so that it looks like a native application with animations, navigation effects, and snazzy presentation. All in all, once minified and gzipped, all this JavaScript is likely affordable for use with high-end mobile browsers, even though JavaScript-based effects may emulate some native effects closely but are never the same in terms of performance. With that said, you’ll need to be able to limit the quantity of JavaScript in your pages if you want to enlarge your mobile horizons to non-smartphone devices. So except for smartphones, consider dropping jQuery and derived libraries entirely. On these non– high-end devices, the chances of encountering quirks, bugs, unsupported features, and unexpected behavior is quite high; therefore, why take the risk? By simplifying your page structure, you still should be able to include some JavaScript-based dynamic behavior that relies only on Document O bject Model (DOM) support and basic language tools. A good rule of thumb is that (with the notable exception of smartphones and tablets) any quantity of JavaScript beyond 10 KB can begin to degrade load time and performance. Note Whether you use jQuery or not, unobtrusive JavaScript always should be your guiding star. Unobtrusive JavaScript means having a place at the start of the code where you attach handlers to elements so that degradation in the case of unsupported features is easier to handle. JavaScript Microframeworks For a desktop site, nobody really minds having a few hundreds of kilobytes in script code. Gmail, for example, fully loaded, usually exceeds the range of kilobytes for loaded JavaScript code. The idea of loading a full-fledged, monolithic JavaScript framework in a mobile site is often unaffordable, e specially if you want to target more than just the top iPhone and top Android devices. Still, it’s useful to be able to use the services of existing code and ready-made frameworks. JavaScript microframeworks come to the rescue. Microframeworks are small, highly focused libraries whose overall size is often only a few kilobytes; sometimes even 1 KB or so. There’s no magic and no special tricks—microframeworks are so small not only because they are minie fi d and gzipped, but also because they take on just one or two tasks. You probably will want to pick up a library for asynchronous (async) loading: one for optimized DOM traversing, one for touch gestures, and perhaps a few more. You can find an interesting list of such microframeworks at http://microjs.com; their average size is around 1 KB. 68 pArt II Mobile Sites One microframework for general-purpose JavaScript programming in the context of mobile sites is XUI (see http://xuijs.com). XUI is not specific to a single task as are some of the libraries listed on m icrojs.com; instead, it’s specifically designed for mobile scenarios, so you can consider it a competitor to other larger mobile frameworks such as jQuery Mobile and Sencha Touch. Unlike these larger frameworks, XUI doesn’t force you into a given programming paradigm or page structure. It focuses on a few tasks (e.g., DOM/CSS management) and totals only 5 KB gzipped. XUI is a good alternative to jQuery libraries for mobile sites and offers a powerful alternative to jQuery libraries for lower-end devices that support JavaScript, DOM, and Cascading Style Sheets (CSS). Chapter 5, “HTML5 and jQuery Mobile,” will cover the whole topic of jQuery Mobile. Sencha Touch is a JavaScript framework, originally created to add touch capabilities to mobile pages, but which is now a full-fledged framework for developing mobile web applications that look and feel native on most mobile platforms such as iOS and Android. You can find out more about SenchaTouch at http://www.sencha.com. More Info A good resource for microframeworks, and for comparing their pros and cons against larger script frameworks such as jQuery, is Addy Osmani’s work at http://goo.gl/jnE9t. Application Device Prolfi es Device fragmentation is huge in the mobile space. If the differences between browsers in desktop site development scare you, then be aware that the mobile space is much worse. On rare occasions, you can get by with just one set of pages for a mobile site. Ideally, you need pages that can adjust intelligently to the characteristics of the requesting browsers. Sometimes you just end up having multiple versions of the same page—one for each device (or class of device) that you intend to support. Alternatively, sometimes you may have one common page template that you fill up with device-specific content. But at the end of the day, these are implementation details. The crucial point is that you need to split your expected mobile audience into a few classes. Then, for each page or view, you provide class-specific markup. This is the essence of multiserving, as b riefly described in Chapter 3, “Mobile Architecture.” Chapter 6, “Developing Responsive Mobile Sites,” will illustrate multiserving with an example. Note In most developed markets today, it is possible to cover most devices with good semantic markup of some kind and then progressively enhance the presentation and i nteraction using CSS and JavaScript. In this regard, the concept of device classes applies to CSS as well: however, if you want to present different content to different classes of devices, then you need to use multiserving because the markup will change between classes. CHAPTER 4 Building Mobile Websites 69Practical Rules to Class Prolfi es In the mobile space, neither the team building a given site nor the team producing a general-p urpose library can afford optimizing pages on a per-device basis—the number of potential devices to take into account is just too large (in the order of several thousand). Hence, a common practice has b ecome to classify all the devices you’re interested in into a few classes. How many classes do you need to have, and how do you define a class? A device class typically gathers all devices that match a given set of capabilities. You define the classes based on the business cases and scenarios. A basic (but still arbitrary) classification may consist in splitting the whole range of requesting devices into three categories: smartphones, tablets, and all other browsers. You provide a rich web experience to smartphones, serve the full site to tablets, and offer plain HTML to all others. How would you define a smartphone? Everyone would agree that an iPhone is a smartphone while, say, a Nokia 7110 is not. The Nokia 7110, released in the fall of 1999, was the first device equipped with a Wireless Access Protocol (WAP) browser. In contrast, the Nokia 6600 certainly was a smartphone when it came out in 2004, but nobody would consider it a high-end phone today. But there are no hard and fast rules. You should know that not only the device classes, but also the rules that determine which class a given device belongs to, are highly variable and strictly specific to a b usiness scenario. At the same time, this lack of fixed rules and practices makes it possible for e verybody to define classes in a way that best fits a given business. All you need is a reliable in frastructure that first identifies the device and then tells you about its real capabilities. I’ll return to that infrastructure in a moment. As a purely intellectual exercise, here are some requirements that identify a modern smartphone in 2012. Note that these are likely to change, even in the near future. ■■ Operating system (minimum version): all versions of iOS, Android 2.2, Windows Phone 7, RIM OS 6, Samsung Bada 2.0, Symbian Anna, and Nokia Meego ■■ Input mode: touchscreen ■■ Screen size: 320 × 480 pixels Admittedly, this definition is rather arbitrary, and it may sound too restrictive for some while being way too relaxed for others. Above all, this definition will become progressively less pertinent as more powerful devices hit the market. A tablet has two main characteristics—it is a mobile device (not a desktop browser), and it has a larger screen than a smartphone. You can probably set the lower boundary to 640 pixels today. It is important to note that grouping all the remaining devices into a single class may be a tough decision. Whether you really want to serve plain static HTML to all of them or further split the remaining devices into two or more classes is up to you. How can you discover the capabilities of the browser for each device? How can you be sure that the requesting browser is really a mobile device? If it’s sufficient for your needs to just check the screen size and screen resolution, then you might decide to go with CSS media queries for high-end 70 pArt II Mobile Sites browsers, and use script code that simulates that on older browsers. Although this a pproach may work in some cases, it’s not a route that will take you far. Instead, relying on a commercial device description repository (DDR) is probably the best way to go. Chapter 6 discusses a few DDR frameworks, focusing in particular on WURFL. Dealing with Older Browsers When I talk to executives planning the mobile strategy of their companies, I often get the impression that when they say “mobile,” they just mean the iPhone and iPad. While it can’t be denied that iPhones and other smartphones are actually responsible for most of the mobile traffic to sites, the mobile universe contains many other types of cell phones and devices as well. Unfortunately, not all of them have the same characteristics, but they are so numerous that you must find a common denominator approach. In the process that you use to identify the device profiles to support, you must define the bottom of the stack at some point. Devices that fall into this sort of catchall group typically are served plain HTML or, at least, the simplest markup that your mobile site can serve. What’s the best way to handle this? When you end up having a catchall device profile, it also means that there’s some rich library you’re relying on for higher-end devices. The jQuery Mobile library is an excellent example. Such mobile libraries sometimes offer to scale down the otherwise rich markup they produce on older browsers automatically. That’s apparently a fantastic deal for you: you write the mobile markup once, and it gets d owngraded automatically for less powerful browsers. Unfortunately, my current experience has not been particularly positive on this point. Although most libraries do fullfi l their promises of downgrading the markup, the quality of the HTML that they produce when that happens is often below your desired standards. You probably want to take care of the HTML being served to older devices yourself rather than blindly relying on the kind of hard-coded markup served by some libraries. The bottom line is that while jQuery Mobile (and other libraries) can truly downgrade HTML based on the requesting browsers, you’ll achieve a better final effect if you manually fix up the output. C urrently, I’m inclined to use jQuery Mobile—but only to serve smartphones and tablets. Note Chapter 5 will cover jQuery Mobile in more detail, including more about its browser-graded support matrix. That feature is orthogonal to performing your own device capability detection, but overall, I prefer to skip the automatic downgrading, at least with the current version of most libraries. Optimizing the payload Minimizing the number of HTTP requests to websites is always a good thing, and it should be a central aspect of any strategy aimed at improving the performance of a site. CHAPTER 4 Building Mobile Websites 71If you have ever tried to use a mobile device to connect to a very basic site with a few plain HTML pages, a bit of CSS, and one or two images over a 3G data connection, you have experienced a delay, or latency. This latency is relevant if the device is not one of the latest smartphones with a powerful processor. In the mobile space, minimizing the total amount of data transferred and the number of requests is not simply a matter of optimization; it is a crucial development point. Over the years, a number of recommended practices have been worked out to help developers build fast websites. Yahoo has been quite active in this field, publishing a very valuable document that you can read here: http://developer.yahoo.com/performance/rules.html. The rules in that d ocument are written for a generic website, but for the most part, they can be applied equally well to both desktop and mobile sites. Here’s a summary of the key suggestions: ■■ Take care of the page structure and find the right place for scripts and style sheets. ■■ Reduce the number of HTTP requests. ■■ Reduce the size of resources. ■■ Maximize the use of the browser cache. Let’s briefly go through the optimization aspects that are most relevant to mobile sites next. the p age Structure A mobile browser may load pages significantly slower than a laptop browser. This means that not just raw performance but also perceived performance is important. Little tricks, such as placing style sheets at the top of the page in the head section help, because doing that means that the body of the page will be ready to render as it is downloaded. The overall download time doesn’t change, but at least users see some results a bit sooner. Similarly, placing scripts at the bottom of the page is helpful because it reduces the impact that synchronously downloading scripts may have on page rendering. When browsers encounter a script tag, they stop page rendering and proceed to download the script synchronously. Page r endering resumes only after the script files have been downloaded, parsed, and executed. When all the scripts are at the bottom of the page, browsers don’t need to interrupt the page rendering process to load scripts; t herefore, browsers are free to concentrate on displaying an early view of the page. r educe the Number of r equests Too many HTTP requests are the primary cause of latency in websites. This statement is even truer for mobile sites. Executing an HTTP request is an expensive operation, especially when that entails connecting to a radio cell. In this case, to preserve battery power, the device sometimes cuts off the connection right after receiving the HTTP response, meaning that to execute another request, a new handshake is required, which consumes both time and resources. For this reason, it is doubly sinful to let links to duplicate resources go unnoticed. Linking a script twice doesn’t affect the rendering of the page, but while the performance hit is negligible on a laptop, it becomes a serious performance hit in a mobile scenario. 72 pArt II Mobile Sites The same can be said for redirects. Each redirect requires two HTTP requests. Avoiding redirects from a site is one way to reduce the number of requests that devices visiting that site have to place. Most ASP.NET MVC books including my book Programming ASP.NET MVC, 2nd ed. (Microsoft Press, 2011) recommend that the Post-Redirect-Get pattern is appropriate for input forms because it saves applications from unwanted F5 refreshes. In a mobile space, that also introduces extra requests; make sure that you make a sound decision about your projects on this point. If you can afford to use AJAX, that would probably be an ideal compromise. Compacting r esources When your goal is to reduce the number of HTTP requests, there’s little better than merging two or more files. Image sprites, for example, illustrate just this point. A sprite is an image that results from the concatenation of two or more images. That way, the browser can make a single request, d ownloading and caching multiple images at one time. Image sprites are not always ideal. Using sprites works great with very small images, such as button icons that are widely used across the pages, but sprites may not be as ideal for the relatively large images used by distinct pages. Downloading a 50 KB image may not be easy over a 3G connection and with an older browser, so if the image is part of a sprite and the sprite size is 100 KB or more, downloading it would take even more resources—probably enough to make the user experience unpalatable. Sometimes, to save an HTTP request, you can decide to encode a small image (one on the order of just a few kilobytes) as a Base64 string and embed it directly in the page. The data Uniform Resource Identifier (URI) scheme just serves this purpose. The data URI scheme defines a standard for embedding data within the page instead of linking it as an external resource. The scheme is defined in RFC 2397; you can read about this RFC on Wikipedia at http://en.wikipedia.org/wiki/Request_for_Comments. The net effect of applying the data URI scheme is that the content of the src attribute of the img element matches the following template: data:content-type;base64,bytes of the image First, you place the data keyword followed by the Multipurpose Internet Mail Extensions (MIME) type of the image. Next, you place the Base64 keyword followed by the Base64-encoded r epresentation of the binary image. If you were embedding an image manually, here’s the markup you would need: img class="image" src="data:image/jpg;base64,/9j/4AAQSkZJRgA..." alt="" / The Base64 image encoding (also known as image inlining) saves a few HTTP requests and improves both the real performance and perceived performance of the page. It is not a feature to use for just any image and page CHAPTER 4 Building Mobile Websites 73Note Most modern device browsers support image inlining, with the sole notable e xception of the Windows Internet Explorer browser embedded in the versions of Windows Phone prior to version 7.5. However, few older browsers support this feature, whose importance decreases as the capabilities and processing power of the browser increase. Improve Your Control over the Browser Cache If the primary objective of a mobile site is to minimize the number of requests, browser caching is the primary tool that you have to manage. Moving auxiliary resources (i.e., style sheets and scripts) to external files often helps. Initially, the number of HTTP requests is higher, but after the first access auxiliary resources are cached, no more requested expiration occurs. External resources are really beneficial if such resources are widely referenced from a variety of pages. In home pages and rarely visited pages, inlining of resources (where possible) may be a better option. In addition, you can drive the browser behavior about caching by using e-tags and Expires headers on your critical resources. Note In addition to optimizing the cache and minimizing HTTP requests, you might want to employ all possible techniques that reduce the amount of data to download. This certainly includes fixes to application logic to return the smallest possible amount of data and markup, but it also includes actions on the infrastructure, such as enabling compression at the web server level and minifying scripts and style sheets. Finally, note that you should always return data as JavaScript Object Notation (JSON) strings rather than XML strings. (JSON was once named the “fat-free alternative” to XML.) The browser cache also applies to AJAX responses. The use of AJAX makes the request go u nobtrusively for the user, who remains in total control of a still responsive page. However, it doesn’t mean that the request will end in a matter of milliseconds. Sometimes caching the AJAX response helps to make most responses really instantaneous. This pattern, however, doesn’t work for all types of requests. If you place a request to read the current balance of an account, you don’t want it to be cached. If you use an AJAX request to auto-complete a text field, you want to cache as much as p ossible. This is to say that control over the AJAX cache must exist, and in real-world scenarios, it must be applied on a per-URL basis. Most libraries, though, offer an all-or-nothing control, which is hardly the right thing for a mobile site. Important As the Back button is the most popular button in a browser, you need to r emember this point: you don’t want the page to reload when you hit that button. To avoid reloading, it is not always enough to set the right cache headers. The size of the elements also matters. The following link provides some numbers. It is a post from a couple years ago, but it is still worth reading: h ttp://www.stevesouders.com/blog/2010/07/12/mobile- cache-file-sizes. 74 pArt II Mobile Sites The Ofifl ne Scenario A mobile site represents an excellent shortcut to implementing a mobile strategy because it brings products and content to a variety of devices without writing a different application for each mobile platform that you intend to support. At the same time, a mobile site requires constant connectivity to work well. This aspect of mobile sites is going to be more and more of a showstopper for sites, and it highlights the key difference between mobile sites and native applications. It’s not coincidental that offline applications have been given a role in using HTML5. Ofifl ne Sites with HTML5 An offline experience without an HTML5-enabled browser is quite hard to achieve; while it’s not impossible, it does require a strong commitment. In other words, it’s not a feature that you would want to offer as a free add-on to a customer When most people talk about ofin fl e sites, they mostly mean online sites that perhaps occasionally experience long downtime periods. The key to surviving such lack of connectivity is caching—in particular, to take advantage of the browser’s ability to cache resources that a user may navigate to later, during a downtime window. These resources include not only auxiliary files, but also AJAX responses. HTML5 lets you create a manifest file and link to it from the html tag of the home page. In this manifest code, you list the files you want to keep cached, which resources are a fallback for other (possibly missing) resources, and which resources are available only while online: DOCTYPE html html manifest="/offline.appcache" ... /html The browser’s ability to cache a subset of the full site on the client isn’t a great thing, per se. It requires more than that to be truly effective. That means is that there is little value for users in just navigating through a few static pages. While that’s considerably better than getting a 404 error message from the browser, it’s not really a decisive change. persisting Application Data Persisting application data locally is another aspect of websites strictly related to surviving an ofin fl e status interval. In an HTML5-enabled browser (again, most browsers in today’s smartphones are H TML5-ready), you use the local storage application programming interface (API) to write name/value pairs in an application-restricted area managed by the local browser. In the near future, the flat name/value format may become even more sophisticated and evolve into a table-based and indexed format. Persistence is also related to synchronization. The ability to persist data locally fully enables occasionally connected application scenarios. At the same time, in an occasionally connected scenario, you might want to offer a read-only view of the data or enable updates. When this happens, you have either the problem of queuing operations or the problem of editing a local cache of data to be synced with the server when the connection is re-established. CHAPTER 4 Building Mobile Websites 75Overall, if you want to build a full-fledged, occasionally connected scenario, you’d better endow yourself with a solid sync framework and/or consider using the OData protocol and facilities for your data exchange. Development Aspects of a Mobile Site Based on the discussion in Chapter 3, the most important task when planning a mobile site p lanning is selecting use-cases. This doesn’t mean, however, that use-case selection is unimportant when developing full sites or other types of applications. It’s just that a mobile application and site are structurally built around a few (and well-chosen) use-cases. Even when you’re simply picking up a use-case from the root site, the way in which you implement it for a mobile audience may require significant changes—possibly a different user interface and perhaps even a different workflow. At this point, let’s assume that you have a well-den fi ed (and hopefully well-chosen) set of use-cases; and let’s also suppose that you have everything required for the back end already in place. You are now ready to start producing markup. But, first and foremost, how do you reach the mobile site? r eaching the Mobile Site A mobile site can be a stand-alone site located at its own unique URL, or it can result from the a pplication logic serving appropriate content to desktop and mobile browsers. In the former case, you just create a new ASP.NET project, design your pages for the mobile devices that you intend to support, give your images and style sheet the size and properties they need, and go. In the latter case, you have a single project where you just handle the desktop full-web case as a special case of a mobile site. Let’s investigate the two options. One Site, One Experience Maybe partly influenced by the One Web vision, I initially approached mobile development with the idea of offering my users just one endpoint and host name. The plan was to hard-code the server with the ability to detect device capabilities and serve the most appropriate content. So my first mobile project was a mere extension of an existing site: I just released a new version of the desktop site with the additional ability to detect mobile browsers and serve ad hoc markup. I had just one ASP.NET project with two distinct sets of pages/views for desktop and mobile. Honestly, this didn’t take much effort to design and implement. It took only a little extra e ngineering to set up a page/view router to distinguish between and serve both mobile and desktop requests. However, testing the site was painful. The only reliable source of information was to use a real mobile device; switching the user agent string on desktop browsers just didn’t work e ffectively. We’ll return to these test issues later in this chapter, and also demonstrate this one-site, one- experience approach while presenting a demonstration of device capability detection. 76 pArt II Mobile Sites The noteworthy point is that when you have just one site that can handle both mobile and desktop browsers, you actually have one set of pages for full browsers and then multiple sets of pages for each class of mobile devices that you support. Really, the desktop becomes the special case What about different use-cases? This isn’t a big issue. You always have a home page in both mobile and desktop environments, so your mobile home page will just offer a different set of links and start a different type of navigation. You only need some logic that, when a new browser session starts, the home page request for http://www.yoursite.com produces the output of default.aspx, default.mobile.aspx, or perhaps default.iphone.aspx. two Sites, One Experience Mostly for ease of development and testing, I soon switched to a different model: two sites, one experience. The mobile site is a neatly separated entity and has its own URL. You have a stand-alone mobile site reachable as a /mobile virtual directory of the main site or as a subdomain, such as http://m.yoursite.com. Sometimes, the site takes its own extension, such as http.//www.yoursite.mobi. Any option that you choose here is equally good, in my opinion, and mostly depends on other aspects of the mobile strategy. In any case, it is always a good advice to provide users (at least on smartphones and tablets) with a link to browse the full site. Because the mobile site is isolated from the principal site, you can test it much more easily— and you can use desktop browsers or mobile generic emulators (such as Opera Mobile Emulator) to p erform quick tests aimed primarily at evaluating the user interface and experience. Obviously, it’s crucial to test on real devices, but for quick tests on markup, colors, position, and flow, using a d esktop program makes the process seamless. Because you now have two distinct sites, you need an automatic mechanism to switch users to the right site based on the capabilities of the requesting device. r outing Users to the r ight Site It’s a mistake to assume a one-to-one correspondence between desktop and mobile pages. This may happen but should not be considered a common occurrence. Note that by saying “page co rrespondence,” I simply mean that both applications can serve the same URL; I’m not saying anything about what each page actually will serve. All in all, we can safely consider only the host name of any requested URL. If the host name belongs to the desktop site and the requesting browser is detected to be a desktop browser, then everything works as expected. Otherwise, the user should be displayed a landing page, where she will be informed that she’s trying to access a desktop site with a mobile device. The user is given a chance to save her preference for future similar situations. The preference is stored to a cookie and checked next. If the request refers to a URL in the mobile site and the user seems to have a desktop browser, consider showing another landing page rather than simply letting the request occur as usual. Finally, if a request is placed from a mobile device to the mobile site, it will be served as expected; namely, by looking into the device capabilities and figuring the most appropriate view. Figure 4-1 presents a diagram of the algorithm. CHAPTER 4 Building Mobile Websites 77Request for a page Request for a page in the mobile site in the desktop site Laptop Device Laptop Device Serve requested Show landing page Show landing page Detect device page for mobile users for desktop users capabilities and serve appropriate content FIGuRE 4-1 The desktop/mobile view switcher algorithm. How would you implement this algorithm? In ASP.NET, the natural tool to implement this routing algorithm is an HTTP module that is a ctive on both sites and capturing the BeginRequest event. The module will use plain redirection or, if possible, URL rewriting to change the target page as appropriate. Here’s some code that implements the aforementioned algorithm in the desktop site: public class MobileRouter : IHttpModule private const String FullSiteModeCookie = "FullSiteMode"; public void Dispose() public void Init(HttpApplication context) context.BeginRequest += OnBeginRequest; private static void OnBeginRequest(Object sender, EventArgs e) var app = sender as HttpApplication; if (app == null) throw new ArgumentNullException("sender"); var isMobileDevice = IsRequestingBrowserMobile(app); // Mobile on desktop site, but FULL-SITE flag on the query string if (isMobileDevice && HasFullSiteFlag(app)) app.Response.AppendCookie(new HttpCookie(FullSiteModeCookie)); return; // Mobile on desktop site, but FULL-SITE cookie if (isMobileDevice && HasFullSiteCookie(app)) return; // Mobile on desktop site = landing page if (isMobileDevice) 78 pArt II Mobile Sites ToMobileLandingPage(app); region Helpers private static Boolean IsRequestingBrowserMobile(HttpApplication app) return app.Context.Request.IsMobileDevice(); private static Boolean HasFullSiteFlag(HttpApplication app) var fullSiteFlag = app.Context.Request.QueryString"m"; if (String.IsNullOrEmpty(fullSiteFlag)) return String.Equals(fullSiteFlag, "f"; return false; private static Boolean HasFullSiteCookie(HttpApplication app) var cookie = app.Context.Request.CookiesFullSiteModeCookie; return cookie = null; private static void ToMobileLandingPage(HttpApplication app) var landingPage = ConfigurationManager.AppSettings"MobileLandingPage"; if (String.IsNullOrEmpty(landingPage)) app.Context.Response.Redirect(landingPage); endregion Once installed in the desktop site, the HTTP module captures every request and checks the r equesting browser. If the browser runs within a mobile device, the module redirects to the specified landing page. The landing page will be a mobile optimized page that basically offers a couple of links: one to the home of the desktop site and one to the home of the mobile site. Figure 4-2 shows a sample landing page viewed with an Android 2.2 device. If the user insists on viewing the full site, then you can’t simply redirect to the plain home page. For its nature, the HTTP module will intercept the new request and redirect again to the mobile landing page. From the landing page, you can simply add a specific query string parameter that the HTTP module will detect on the successive request. Here’s the actual link that results in Figure 4-2: a href="http://www.easycourt.net/contosoen?m=f"Full site/a You are responsible for defining the query string syntax; in this case, m stands for mode and f for full. The task is not finished yet, though. At this point, users navigate to the home page of the site. What about any other requests? Those requests, in fact, will be intercepted by the HTTP module. By adding a cookie, you can provide additional information to the HTTP module about requests d eliberately sent to the desktop site from a mobile device. CHAPTER 4 Building Mobile Websites 79FIGuRE 4-2 The landing page of the EasyCourt demo site. How can the user switch back to the mobile site? Ideally, any desktop site with a sister mobile site should offer a clearly visible link to switch to the mobile version (and vice versa when the full site is viewed on a mobile device). If not, the user won’t be offered a chance to choose the full or mobile site until the cookie expires or is cleared. To clear cookies, users deal with the Settings page of the mobile browser. Adding Mobile Support to an Existing Site Where do you place the landing page? Is it on the desktop or on the mobile site? In general, it doesn’t matter; however, if you put it on the mobile site, then you really can enable a scenario in which you deploy a mobile site with all the required routing logic without touching codebase of the existing desktop site. In the demo site of EasyCourt, a commercial booking system for tennis courts, which I introduced in Chapter 3, I just edited the Web.config file of the desktop site and deployed a library with the HTTP module in the Bin folder. No changes were made to the source code. Here’s the configuration script to add a router HTTP module to the desktop site: system.webServer modules add name=”MobileRouter” type=”...” / 80 pArt II Mobile Sites /modules ... /system.webServer The Welcome page was defined on the mobile site. Note that the Welcome page always should be visible, and it never should need authentication. Depending on how you deploy the mobile site—a distinct root site/application or a child application/directory—you may need to tweak the Web.config file of the mobile site to disable the HTTP module. If the mobile site is a distinct application, then it needs its own Web.config file that has been fully configured with the HTTP module. If the mobile site is, instead, hosted as a child directory in the desktop site, then it inherits the configuration settings of the parent site (the desktop site), including the HTTP module. To speed up requests, you might want to disable the HTTP module in the mobile site. Here’s the configuration script that you need in the mobile site’s Web.config file. The script clears the list of HTTP modules required by the mobile site: system.webServer modules clear / /modules ... /system.webServer In addition, you need to instruct the parent application/site explicitly to stop the default in heritance chain of settings. Here’s what you need: location path="." inheritInChildApplications="false" system.webServer modules add name="MobileRouter" type="..." / /modules ... /system.webServer /location Also, notice that when the mobile site is a child application/directory, then it inherits a bunch of settings (for the section where inheritance is not disabled) that don’t need to be repeated (for example, connection strings and membership providers). Note This example is based on the default Internet Information Services (IIS) 7.5 c onfiguration—integrated pipeline mode. If you’re using the classic pipeline mode, then instead of system.webServer/modules, you should operate on the system.web/httpModules section. CHAPTER 4 Building Mobile Websites 81Design of the Mobile Views Mobile websites normally show a subset of the content offered by a desktop site. For example, if you have a three-column layout in a desktop site, you probably want to remove (or move to additional pages) content displayed in two of the three columns. Reducing the amount of information improves the load time of the site and makes better use of the available space. “Shrink-and-t fi ” is a popular slogan. An ideal layout for pages of a mobile site is based on a single column. The font size is large enough to allow easy reading without zoom. The search bar (if any) ideally will go at the top, and navigation links are commonly placed at the bottom. You might want to place a link to the desktop version of the site somewhere on the mobile site. Scrolling is accepted, especially vertical scrolling, but endless lists are annoying. Let’s briefly review some common scenarios now. Input Elements On a typical mobile site, most of the functionality is read-only. This fact seems to suggest that you are not going to have that many chances to write input forms, and perhaps even that input forms are not an aspect of development you want to invest much time in. This is just wrong. Exactly because most of the functionality is read-only and a mobile device is tiny and not as p owerful as a laptop, providing specific and restricted parameters is key. To type query parameters, or to specify settings, input forms are a common presence on mobile pages anyway. Some typical web and Windows controls need fixes, though, especially in light of the touch capabilities of many devices. Typing text on mobile devices is hard and should be minimized. As we’ll see in later chapters, this is easier to achieve with native applications, where you can control the input scope of soft keyboards and attempt to display an optimized subset of keys to the user. In mobile sites, all is left to the browser, although developers can use forms of auto-completion via AJAX. If the browser understands HTML5, then you can just use the most appropriate type attribute on the input element and let the browser do the rest. To be honest, what you get may differ quite a bit, even on smartphones. For example, numbers and ranges are well supported on both iPhone and Android at present, but the date type produces just the plain text box on Android. In iOS5, however, the browser recognizes your intentions and displays the compelling iPhone date picker element (see Figure 4-3). On the other hand, iOS still lacks the ability to upload files from the browser, which is a feature available in Android mobile browsers. In general, data entry should be redesigned and even rethought case by case. For example, when it comes to booking a tennis court in EasyCourt, the site offers a drop-down list with ready-made dates, as shown in Figure 4-4. It should be noted, however, that this particular screen is not mobile-specific but simply represents the plain transposition of a desktop page. You always should wonder if there may be an innovative way of letting users enter their choices. Don’t stop at the classic, desktop-oriented way of building input forms. Mobile is different and user-centered. 82 pArt II Mobile Sites