Going Offline with HTML5 and JavaScript, Part 1

There are two primary use cases for going offline with mobile HTML5 web applications and JavaScript: partial offline and full offline. Before diving into building offline apps, understanding the differences between these use cases will help you build the best applications for your requirements. The functionality in modern browsers has finally gotten to the point where it is feasible (and fun!) to build offline web applications.

Partial Offline. Partial offline means the vast majority of the time the application is online, however it can continue to work if the internet connection gets temporarily interrupted. A partially offline app understands that requests for remote resources, that is resources that don’t exist on the device, will automatically defer to local resource, or at least fail gracefully, during the period of time when an internet connection doesn’t exist. Partially offline apps typically cannot be reloaded or restarted offline. The coding required to handle this scenario is much lighter weight than the architecture required for going fully offline. An example of partial offline is a reader app that pre-caches certain HTML pages of your choice. If the internet connection gets disrupted you can continue reading and navigating between the cached pages.

The partially offline scenario exists because there is no such thing as a perfect internet connection for mobile. In reality, internet connections and download speeds are very choppy when measured over a period of minutes or hours. Sure, some internet providers market 4G connections as being extremely fast, or have the best coverage etc., etc., blah. The bottom line is cellular and even WiFi internet connections are not guaranteed. A good example of this is coffee shops. They don’t come with an uptime guarantee, so if a couple of yahoos sitting next to you are streaming HD Netflix then that will surely bring the internet connection to its knees.

In reality, if you don’t live danger close to a cell phone tower and are moving around doing your job or running errands chances are your internet connection will fluctuate up and down over time. Anyone that owns a smartphone has experienced this at one time or another. Dropped calls are perfect example. You may be shopping and going in and out of buildings, or hanging out in the back of a taxi, sitting in your car pulled off the side of the road, or perhaps even just watching your kids as they play in the neighborhood park. A web application architected for partially offline will let you keep surfing or working for a short period of time, and hopefully long enough until the internet connection comes back up.

Full Offline. A fully offline JavaScript application is one that starts out online to download all the necessary data and files, then it can be completely disconnected from the internet. These apps can survive browser restarts and reloads, they can stay offline indefinitely and/or they can be resynced online at some point in the future.

Fully offline apps need to be architected in a much more robust way than their partially offline cousins. Partial offline apps can be considered more fragile than fully offline apps because they can’t be restarted or reloaded while offline, and you have to be very careful to limit their capabilities while offline otherwise the user can easily break the app. Fully offline apps are built with the knowledge that they may be offline for extended periods of time and need to be self-sufficient because users will be depending on them. If a fully offline app breaks then the user will be completely hosed (and very unhappy) until some point in the future where the internet connection can be restored and they can resync the app.

Offline apps can break in any number of interesting ways such as throwing a 404 when the user hits the back button or simply crashing when the app unsuccessfully attempts to a load a new page. By their very nature, fully offline apps may have larger and more complex data storage and life cycle requirements. They cache entire HTML web pages and all their associated JavaScript libraries, images and supporting data.

Examples of full offline apps include mapping apps, web email, reader apps, and any other apps that require information from a database.  User data is typically downloaded locally, stored on disk and then accessed by offline web applications. Any data that’s stored in memory will be lost when if the device or browser is restarted while offline.

 

Web offline versus Native offline

When building out your requirements, it’s a best practice to do an honest comparison between offline web capabilities and the offline capabilities of native SDKs.  In general as of the writing of this post, it’s fair to say that native apps still offer much more robust offline capabilities than the latest versions of mobile browsers. There are a few exceptions where browsers may have similar capabilities but almost always the level of control is more limited.

Native apps have the advantage because they basically have direct access to the device operating system and many of the capabilities are simply integrated into the respective SDKs. Here is a partial list of capabilities that are commonly seen in native offline requirements:

Web apps, on the other hand, run within the browser and are subject to any limitations imposed by the browser. The browser, itself, is a native app and it restricts it’s own children (web apps) to certain security restrictions. A few examples of web app limitations include:

  • Access to a limited number of censors. Access is not consistent across different browser types.
  • Limited control over location services via HTML5 Geolocation API.
  • JavaScript cannot programmatically read and write non-cached files on the device without user intervention.
  • Internet connectivity detection typically dependent on 3rd party libraries such as offline.js. Support is inconsistent across some platform/browser combinations.
  • Indirect and limited control over battery life and optimization.
  • Browsers and any of their associated tabs stop running as soon as the browser is minimized. If you have a requirement for the app to “wake up” from a minimized state under certain conditions you will have to go native.

 

Summary

Partial offline applications are design to continue working gracefully during intermittent interruptions in connectivity. Because offline is considered a temporary or even momentary condition in this use case, partial offline apps can use lighter weight architecture and have smaller data storage needs than full offline apps.

Fully offline apps are designed to be taken offline for extensive periods of time. They have to meet more demanding requirements and need a comprehensive architecture that enables storing of HTML files, JavaScript libraries, and user data as well as being able to handle browser reloads and restarts while offline.

Lastly, when having conversations about building offline apps you should weight web versus native offline capabilities against your requirements. Native SDKs still offer much richer control over most of the aspects of offline functionality.

Stay tuned for additional posts on this subject. Part 2 will look at the features and APIs you can use to take applications offline.

 

References

10 ways to deal with intermittent internet connections

How accurate is Android GPS? Part 1: Understanding Location Data

Wikipedia – Browser Security

Mobile web developers: let users adjust font size

Many consumer web sites have done a fantastic job of deploying mobile web versions of their sites. However, over the last year I have heard an increasing number of complaints about websites specifically designed for mobile: you simply can’t adjust the font size. Depending on the device’s screen size, this can potentially cause painful choices: either deal with (usually) tiny font sizes and struggle to read content, or go to the full web site and be relegated to panning, zooming and rotating between portrait and landscape mode to try and fit as much content as possible onto a tiny screen.

To me, the solution is easy: allow users to set their own font-size. Here’s an example of settings I’m referring to, specifically setting the viewport’s user-scalable property to ‘no’ is what’s causing the problem:

<meta name="viewport" content="width=device-width, user-scalable=no">

There are certainly use cases, such as mapping applications, were you might want to prevent user scaling because it will affect other components inside the application.  However, if there aren’t any components affected by pinch zoom then you most likely can set the user-scalable property to yes, or simply omit the property.

My first suggestion is provide users with the ability to adjust the font size.  Here is an example that will let the user adjust font size for a specific DIV:

<meta name="viewport" content="width=device-width">
<script>
    var up = 1;
    var down = -1;
    var elementSize = document.getElementById(“someDiv”) .style.fontSize;

    function increaseFont(){
        up++;
        elementSize = up + “px”;
    }

    function decreaseFont(){
        down--;
        elementSize = down + “px”;
    }

    function resetFont(){
        elementSize = “14px”;
    }
</script>

Another option is to combine the above suggestion with media queries to adjust font-size automatically based on screen size, pixel ratio and/or min-resolution. Here is one example:


@media
(-webkit-min-device-pixel-ratio: 2),
(min-resolution: 192dpi) {
    body{
        font-size: 16px;
    }
}

Other examples of media queries can be found here: css-tricks.com.

What all mobile web devs should know about PhoneGap

If you already building or looking into getting started with mobile web applications you should understand the basics of PhoneGap. The name ‘PhoneGap’ is widely recognized, and perhaps more widely misunderstood.

The nudge to write this article was born out of conversations where we stumbled across concrete limitations to modern responsive JavaScript libraries such as bootstrap and jQuery. Limitations that cannot be overcome by adding more brilliant functionality because some JavaScript capabilities simply do not exist within the browser today. Furthermore, other requirements were imposed by political realities, timeframes and expectations.

That’s where PhoneGap steps in. 

So what, tell me what PhoneGap does?

PhoneGap is owned by Adobe and it has an open source top-level Apache Foundation sister project called Cordova. I won’t bore you with its long and twisted history, you can read about it here if you want.

The bottom line is PhoneGap allows you to develop JavaScript mobile applications that have access to certain aspects of the native device such as writing data to a filesystem. Your web application is wrapped within a native mobile application container that gives you JavaScript access to native operating system capabilities beyond what the browser itself is capable of doing!

By native I mean iOS Objective C, Android Java, WindowsPhone, Windows 8, Blackberry 10, Amazon Fire OS and Tizen. Your JavaScript applications runs in a chrome-less browser that gives you special hooks to the operating system. You can also submit PhoneGap applications to the AppStore, Google Play and others.

Who uses this stuff, well you may be using a PhoneGap app from one of these online stores and not even know it. To mention a few: Southwest Airlines and many others.

What limitations can PhoneGap address that responsive libraries don’t?

If your requirements call for all or most of the following items, then PhoneGap is the correct choice for your project today. That may change as HTML5 continues to rapidly grow, but for now I’m sticking with the following bullet points. Stick with me and read through all of these before starting to throw out counter arguments.

JavaScript skillz. If you are an existing JavaScript shop, then PhoneGap leverages your existing JavaScript skills to access capabilities beyond current browser functionality without the need to have an in-depth understanding of Objective C or Java.

Sure, it’s easy to say you can hire expert contractors to develop iOS and Android applications, along with UX designers and testers. But, if your budget doesn’t include the capital costs for these folks and all you have is JavaScript ninjas on staff then the choice is easy.

Or, maybe you have genius-level developers that could easily and quickly spin up on all your need to know on ObjectiveC and Java Android. If this isn’t the case, and your timeframes and budgets don’t allow for this then you’ll need a fallback plan such as PhoneGap.

Access to camera.  Yes, you can currently access the camera on some web browsers today. However, the support on mobile browsers is still inconsistent, limited or non-existent. On the other hand, native device OS’s are expected to have access to cameras If they didn’t it would be considered a serious oversight. PhoneGap provides cross-platform mobile device access to the camera.

Read/write access to SD Card. Just to reiterate, this is both read and write access to a local storage device. Certainly there is a FileReader API in plain old JavaScript, but as far as I know there isn’t a FileWriter or its equivalent yet. If you need the write access to go along with read capabilities then you should be looking at PhoneGap.

[Correction Jan. 27, 2014] I mis-wrote. The FileWriter API exists however it has limited supported across browsers: https://caniuse.com/#search=filewriter. And, examples of it’s use can be found here.

AppStore or Google Play. If you have a requirement to submit your application to the app store then PhoneGap will help you get there. There is no way today for submitting a stand-alone web application for acceptance on AppStore or Google Play. Period. Some will argue that the need for using these online application stores is going away, but that’s a non-issue if you have been directed to meet this requirement a.s.a.p. and your job depends on it. If that’s the case, then PhoneGap will be your friend.

Is there anything else I should know?

Yes…First, PhoneGap is not perfect, but then again few software projects are perfect. You will need to install and know a few things about the native IDEs you want to support. If you want to deploy Android you’ll need to install Eclipse or IntelliJ. For iOS you’ll need to install XCode. Etc. You still have to compile a native project or you can try your hand at Adobe’s PhoneGap Build, which is a cloud based build system for PhoneGap.

It is confusing that there are two projects that share a common/similar code base: PhoneGap and Cordova. Also, Cordova’s documentation has typically been more up to date that Adobe’s. If you do your research you’ll find various performance complaints and bug issues (like I just said are there any software projects that don’t have these??).  Yet, overall it’s a great starting point if you have the needs listed above, and it’s much better than trying to start from scratch given today’s dramatically shortened delivery expectations.

You can absolutely still use bootstrap, jQuery and other JavaScript libraries within PhoneGap. There are caveats, of course, related to application life-cycle issue, navigation as well as App Store and Google Play user interface acceptance guidelines.

If you want to add functionality to PhoneGap because you find some critical thing is missing that you need for your project, the good news is you can develop a custom plug-in.

Last, I should mention Titanium Studio. It also lets you leverage JavaScript skills, with the primary difference being that it converts JavaScript into native byte code rather than just displaying it in a chrome-less view.  Plus it’s comes with its own IDE and MVC Framework.  I’ve never used Titanium so I can’t judge it, however I know people who do use it successfully and love it. It’s one more thing to consider that you should be aware of.

References

Cordova Documentation

PhoneGap Documentation

PhoneGap Platform Support