Escape Velocity of HTML5

A Complex Choice

Some teams choose a mobile platform with little deliberation.  For example, HTML5 may be the obvious choice for a multi-platform content-driven app, but to support facial or speech recognition, native is still the only option.  For other apps, though, platform selection can be difficult due to competing forces of maximizing distribution, schedule pressure, minimizing development effort, and needing native platform features like widgets, cameras, notifications, and intents.

Even after an app launches, it may pay to reconsider the platform options, keeping in mind that the choice isn’t binary.  For example, Facebook for iOS launched as mostly HTML5 packaged as a native hybrid, but recent versions improved scrolling and load times by replacing much of its HTML5 code with native, shifting toward the native end of the hybrid spectrum.  Virgin Active Australia health clubs, on the other hand, moved in the opposite direction after its initial launch, replacing its native iPhone app with the HTML5 app “mylocker”.  By switching to HTML5, they tripled their potential audience, eliminated Apple’s review delays, and reduced maintenance costs.[i]

This post highlights platform selection challenges and corrects some mistaken assumptions about the HTML5 stack (including CSS-3, Web SQL, etc.) as a mobile app platform.

The Rejection of Write Once, Run Anywhere

Many web developers have had miserable experiences due to browser feature fragmentation. For example, older browsers had conflicting box models and some desktop browsers support Indexed DB instead of the de facto Web SQL mobile standard. And anyone who has only tried immature HTML5 tools may still be convinced that “write once, run anywhere” is a pipe dream. By contrast, the simplicity of developing a single-platform native mobile app is compelling. On closer inspection, though, a full indictment of write-once-run-anywhere is premature and the outlook is bright for mobile HTML5 apps.

The flipside of fragmentation woes is the broad reach of device diversity.  According to IDC, Android accounts for 68% of smartphones worldwide, iOS for 17%, and the remainder is split between Blackberry, Symbian, and Windows Phone. iOS has a larger market share in U.S. enterprises, but single-platform apps undeniably ignore a big potential audience.

One way to ease fragmentation challenges is to acknowledge that mobile apps only run on mobile devices.  That is, it’s safe to ignore desktop browser inconsistencies when building a mobile app.  Some HTML5 features differ between mobile platforms, including camera access (unsupported before Android 3.1) and WebSocket for 2-way streaming (only recently supported on iOS), but such features are not critical for most apps. Most mobile devices (including Android 2.3+ phones, Android tablets, BlackBerry 9800, BlackBerry PlayBook, iPad, iPhone, iPod Touch, and Kindle OS tablets) are remarkably consistent in the HTML5 features needed for a robust, high-quality mobile app.

Features That Mobile HTML5 Apps Should Be Using

Most smartphones and tablets support offline mode, Web Storage, Web SQL, CSS-3, canvas, geolocation, and video playback.  Those features alone enable great HTML5 apps that work on 95% of mobile devices.

Offline Apps

A cache manifest lets users download and run an HTML5 app unimpaired even when the network is slow or unavailable.  Such apps can also use HTML5 networking APIs to check connectivity details and react to going online or offline, or to switching between fast WiFi and slow carrier network.  To work best offline, typical content-driven HTML5 apps should pre-fetch data while on WiFi and show cached content while connectivity is poor, e.g. while in airplane mode or, for large downloads, while on 3G. The goal is high speed and reliability everywhere – at home or work, on the road, or in an elevator or parking garage.

Web Storage

HTML5 apps can store 5 megabytes of data in a thread-safe “Web Storage” sandbox accessible only to Same Origin apps (those in the host domain).  This can be in Session Storage that expires when the app closes, or in Local Storage that persists through subsequent launches.

Security architects may be wary of storing sensitive data in Web Storage.  Considering HTML injection, click-jacking, and cross-site request forgery, their initial concern is understandable but safety can be assured by adopting a few basic rules that allow Same Origin Policy to protect Web Storage data to the same degree as native stores (e.g. user preferences, app settings, and flat files):

  1. Use SSL and a trusted server certificate to prevent DNS spoofing.
  2. Only send sensitive data to authenticated, authorized users.
  3. Secure all scripts on the host domain.
  4. Do not run scripts from untrusted sources.

That is, configure HTTPS properly, confirm user credentials before sending data, block rogue JavaScript (i.e. don’t host a wiki or raw user comments on the secure app’s server), and if any remote code is involved (e.g. through JSONP), only load it from other secure servers.

Beyond that, if an app needs even more security, perhaps matching the rarely used Enhanced Data Protection APIs available to native iOS apps, it can encrypt sensitive data with a secure key before storing it.  Choose a public key encryption technology (e.g. RSA) and secure the data access key by obtaining it with each launch, typically with a user password hash and/or from the server if the device is online.

Web SQL

Some confused assumptions about Web SQL stem from the fact that its standardization process has stalled.  The stall occurred because all Web SQL implementations use SQLite but the standards body needs an alternative implementation to create an open standard.  Some people conclude that HTML5 apps cannot rely on Web SQL.  In reality, it’s safe to use in mobile apps because all major mobile devices support Web SQL consistently.

As noted above, Facebook’s native/HTML5 hybrid app had performance problems. Each refresh of the timeline downloaded all the content as one big HTML page, and the app only cached images, stylesheets, etc. in its UIWebView.[ii]  Facebook replaced that with native iOS code, but they didn’t have to go that route.  They could have improved download speed by caching timeline entries in Web SQL and aggregating them in the app to minimize bandwidth.

A common misconception is that the 5 MB limit of Web Storage applies to Web SQL. Actually, HTML5 apps can store up to 1 Gigabyte of relational data in Web SQL, with one caveat: apps need user consent to increase a Web SQL database more than 5 MB beyond the previous allocation.  That could be annoying if the database keeps growing, so better is to avoid repeated prompts by estimating long-term storage needs and reserving Web SQL space in advance.

Another point of confusion is around the asynchronous query model of Web SQL.  Novice developers may need to adjust to the asynchronous model.  Rather than an impediment, though, that architecture is a clear benefit because the UI of a properly designed HTML5 app remains responsive while it queries Web SQL.

Finally, as with Web Storage, some concerns about Web SQL relate to data protection.  Simply put, the Same Origin Policy of Web Storage applies to Web SQL.  Sensitive data is as safe in Web SQL as it is in Core Data or native SQLite if the HTML5 app only serves authorized users over trusted SSL and its scripts are secured.  For additional protection equivalent to Enhanced Data Protection, a secure key issued per launch can encrypt and decrypt Web SQL data.

Pixel-Perfect Graphics

Spacer images, <table/>s for columns and footers, deeply nested <div/> layouts, and other hacks should go extinct along with HTML 4.  Using CSS-3, designers have control of layouts comparable to combining universal binaries, springs and struts, and auto-layout in native apps.  Complex views can have clear, maintainable markup, with alternate layouts and resources for tablet vs. various phones, portrait vs. landscape, print, etc.

The static, grainy, stretched images of legacy web apps should also go extinct thanks to the HTML5 canvas for rendering arbitrary graphics on the fly. UI options should now be bound only by the creativity and innovation of designers and developers. (See http://hakim.se/experiments.) Native graphics do have the performance boost of GPU acceleration and multithreading, but the graphics engine behind the HTML5 canvas also uses hardware acceleration on most newer mobile platforms. HTML5 games (e.g. HTML5 Pacman) show that HTML5 graphics are powerful enough for most apps.

Video Playback

One contention is that HTML5 does not standardize a video encoding format.  To support video on all HTML5 browsers, multiple encodings are created and each browser selects the format it supports. For mobile apps, though, that complaint is inconsequential because mobile devices all support MP4+H.264 video with mp3 audio.

Another point of consternation is that HTML5 does not support streaming or DRM.  If streaming or DRM are required, though, there are several third-party solutions, but with certain limitations (e.g. iOS only streams HTML5 videos in full-screen mode, pre-ICS Android devices fall back to Flash for video streaming, and DRM isn’t actually bullet-proof even for native apps).

Geolocation

Location awareness has found its way into all kinds of apps. Mobile apps can use HTML5’s geolocation API to get the device GPS coordinates, altitude, heading, and speed, and to be notified of movement (GPS movement in all cases, and fine-grained accelerometer info in iOS and Android ICS+ through the “devicemotion” and “deviceorientation” events).

Features That Mobile Native Apps Are Using

Each platform has a look and feel that users expect from its apps. For example, long pressing on Android typically presents context actions, and date pickers vary by device.  Native apps tend to expose platform-specific features like home screen widgets, status bar notifications, buttons (search, volume, menu), intent registration, camera, microphone, etc. HTML5 apps typically ignore such platform specifics.  This would seem to give native apps a clear advantage.

Trouble eventually arises when pressure mounts to port a single-platform app to another platform.  New designs, layouts, and media assets must accommodate new screen dimensions, and some features that are natural in one platform are awkward in others.  The pain of cross-platform development, then, often traces back to designs written for a particular device.  For example, a simple 3D page flip in a native iOS app is difficult to port precisely to Android, as is porting cross-app sharing of rich data from Android to iOS.

So, a native app may need to drop or change features to be ported to a new platform, which lessens the native advantage. A neutral look and feel may be appropriate for some apps, even for successful and popular games, Twitter clients, etc.  If an app does need native features, though, that’s often feasible in HTML5 with some extra development effort and/or with native packaging, e.g. through Sencha Touch, Titanium, PhoneGap, Appcelerator, or Apparatio.  Instead of designing features for just one device, teams should acknowledge the platform differences early, create platform-neutral features optionally with platform-specific variations, and accommodate device diversity as a matter of course.

Discovery and Monetization

Google’s Play Store and Apple’s App Store (and Amazon’s Appstore to a lesser extent) are major driving forces for mobile because users can easily discover apps by browsing, searching, and reading recommendations. Pure HTML5 apps, by contrast, are typically discovered through links from search engines, web-based app catalogues, social networks, and even text messages. Despite some obscure HTML5 app stores (OpenAppMkt, Zeewe, etc.), there’s no definitive place for HTML5 app discovery, rating, and commenting.  So, users may not discover an HTML5 app as easily as a comparable native one.

Monetization is often the end goal.  In this regard, native apps have the advantage of consistent and secure payment frameworks through the app stores (Amazon’s, Apple’s, and Google’s) for one-time payments, subscriptions, in-app purchases, and advertising.  A notorious drawback of native payment frameworks, though, is a 30% surcharge.

HTML5 apps are often monetized through advertising and subscriptions, but without the ease of the native payment frameworks.  On the other hand, they avoid the surcharge and retain control of the customer and transaction data, which is precisely why the Financial Times abandoned their native subscription app for HTML5.

If discoverability and the payment frameworks of native app stores outweigh the surcharges and loss of data control, developers can easily package HTML5 apps in native wrappers to publish through the native app stores.  A great example of this approach is Boom Town, an HTML5 app built in six weeks and deployed simultaneously to Apple’s App Store, Google’s Play Store and Chrome Store, and Facebook.

Developer Experience

Developers write native apps with sophisticated software development kits like XCode and Eclipse.  Some of these tools are so good that some developers are reluctant to embrace HTML5 based on tools alone.  Fortunately, the HTML5 tools have been evolving.

Debugging

HTML5 developers typically debug through WebKit’s Web Developer Tools.  Most have used the tool kit’s basic debugging features, but many are unaware of some of its advanced capabilities.  For example, the debugger has features like watch expressions, scope variable state (including closures), step in/over/out, call stack navigation, and conditional breakpoints.  The DOM inspector manages DOM elements, CSS styles (including active/focus/visited diagnostics and converting colors to hex, RGB, or HSL), metrics (position, margin, border, padding, size), etc.

For mobile app development, the WebKit Developer Tools can emulate touch events, set the screen resolution, and manage the offline app cache, Web Storage, and Web SQL.  They can monitor network requests and responses, showing the URIs, HTTP methods, response status, MIME types, initiators, resource size, latency, and graphical timeline.  The WebKit Profiler rivals the one in Instruments, optionally inverting call trees, tracking time/percentage, filtering events, and snapshotting the heap to isolate memory issues.  It can even audit network utilization and script performance, then automatically recommend optimizations like combining CSS, enabling compression, leveraging the browser cache, reordering resource loading, or removing unused CSS.

Application Frameworks

A complex app may be difficult to implement and maintain without an application framework.  Thanks to Appcelerator, Google, Sencha, and other vendors, HTML5 apps can follow familiar architectural patterns and build on rich controls to shorten development timelines.  As just one example, consider the framework from Sencha.

Sencha Touch 2 is a mobile HTML5 app development framework based on Ext JS 4. It has rich documentation, training, support, and an active community. Its “visual app builder”, Sencha Architect 2, lets designers prototype apps and helps developers turn prototypes into full scale MVC apps.  Sencha includes a sophisticated layout engine, application cache management, state management, hundreds of built-in icons, theming, and extensible base classes including 50+ UI view components (e.g. navigation controllers, split views, lists, carousels), object stores (e.g. in-memory, Ajax-REST-based, or Web-Storage-backed), and models for easy data binding.

Sencha also builds HTML5 apps for various types of distribution. Its native packaging mechanism exposes native device APIs (e.g. for the camera) and compiles to native binaries to distribute through the App Store, Play Store, enterprise app catalogs, etc.  The HTML5 build system minifies apps and generates a cache manifest for app downloading.  The resulting apps can install to the home screen, run offline in full screen, and use hardware acceleration, fluid animations, and smooth scrolling with momentum.  Properly designed, these apps look polished on all major mobile devices and feel as fast and natural as native equivalents.

Other mobile app frameworks have comparable benefits.  For example, the Google Web Toolkit lets developers write a mobile app in Java with Eclipse, debug it, and compile it into optimized JavaScript.  It provides backing stores for client-server or Web Storage, canvas visualizations, and widgets for audio and video.  Adobe’s mobile HTML5 app development suite includes Adobe Edge (design tool to build reusable, interactive components for HTML5 apps using timelines and motion), Dreamweaver CS6 (visual development environment for HTML5 apps and web sites, supporting PhoneGap, jQuery, etc.), and ColdFusion (server-side technology exposing WebSockets, charting, video, and push services).

Lift Off

HTML5 is not just a set of specifications with a promising future.  It is ready for developing mobile apps today, with mature tools and frameworks and enough consistent feature support to build complex, high quality, offline capable apps that rival native equivalents yet run on 95% of Android, iOS, Windows Mobile, and Blackberry phones and tablets.  Although some apps are still best suited for native (e.g. machine learning apps that interpret images or sounds), others with constrained budgets or timelines are ideal for HTML5 if broad reach is desired.  Alternatively, a native/HTML5 hybrid may be best for a multi-platform app that needs some native device features, turnkey monetization, or maximal discovery through multiple native app stores.

Major companies including Amazon, BBC, CBS News, CNN, Comedy Central, ESPN, Fox Sports, Google, Kayak, LinkedIn, Mafia Wars, NBC, The New York Times, NPR, Subaru, Twitter, Walmart, Wikipedia, Yellow Pages, YouTube, and Zillow already acknowledge the advantages of mobile HTML5 apps and offer them exclusively or as an alternative to their native apps. For multi-platform mobile apps, HTML5 has reached escape velocity.  Come along for the ride.

About rodasmith
Rod is a Slalom Consulting Solution Architect and software developer specializing in mobile applications for HTML5, Android, and iOS, with a passion for natural language processing and machine learning.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: