For Developers: Making a Solid Connection With your HTML5 / Javascript Mobile App

macgyver_mobile_application

Recently, I had the opportunity to build a mobile application for Siena Heights University called “SHU Mobile”. View more details or download SHU Mobile for Android.

I am very happy with the end result of this project. The application is working well and very stable while using a code base that is compatible with multiple devices including iPhone and Android phones. 90 to 95% of the app code will be used in making SHU Mobile available for iPhone in the near future.

The purpose of this post is to summarize the techniques used to make SHU Mobile great. This is exactly the type of summary I would have benefited from reading in the early stages of SHU Mobile application development. If you are a developer or have a curious mind, maybe you will also benefit from this post.

—————————

There are two major ways to build mobile applications:

  • #1 Use the native platform development language code
  • #2 Use web technologies, Javascript and HTML5, for 90 to 95% (arbitrary) of the development

Pros of Native Mobile App Development:

  • You can do more complicated things with less ‘tricks’ or what I like to call ‘MacGyvering’ because the native code is especially built for just that
  • There is more support for native development

Cons of Native Mobile App development:

  • You can’t reuse your developed code for other platforms. For example, iPhone’s Objective C code can’t be used for an Android device that expects Java code. This is a huge drawback since it requires you to rewrite your entire app for each type of unrelated device that must run the app.
  • Developers must master a greater number of coding languages in order to support multiple types of devices

Pros of HTML5 / Javascript Mobile App Development:

  • You can reuse 90 to 95% of your code on different devices, including iPhone and Android. Note: This is made possible with the help of open source software, such as
    Phone Gap. At the time of this writing, phone gap is open source software; free to download and use. Code portability on multiple devices is a huge benefit since it can save you hundreds of hours in development / maintenance time.
  • Developers, who are already familiar with web development, can reuse this web knowledge to make great apps.

Cons of HTML5 / Javascript Mobile App Development:

  • In order to implement more advanced mobile app functionality, you may have to resort to more MacGyvering since
    web technologies aren’t focused on mobile app development alone. Therefore, building certain functionality may be less straight-forward.
  • There is less support for HTML5 / Javascript mobile app development compared to native mobile development.

My HTML5 / Javascript app relies on external data. How can I make a solid connection?

So you have chosen to use HTML5 and Javascript to build your app in order to make it more portable on different devices. Great. What principles should you consider and what are some techniques you could employ to make your mobile application seem reliable, fast, and fresh to an end user?

Should be…

  • Reliable: Your app shouldn’t crash or stall, even if it needs to download large amounts of data, such as many recent news articles.
  • Fast: Mobile devices have less processing power than laptops or desktops. It’s normal for a phone to take 10+ seconds to download 1.5 MB over 3G. To your end user, 10 seconds is an eternity. You should find ways to distract your user while your application downloads new data. In most cases, a progress bar or pinwheel is enough to reassure the user that your app hasn’t stalled.
  • Fresh: If the main focus of your app is external data (recent news) then it must be able to successfully connect with the latest information. Your download of new data shouldn’t fail, even if the data is large enough to potentially cause a time out issue in your app. Also, make sure you application doesn’t ignore updated external resources because older versions of external resources are being cached.

Making it so

You know how your app should behave. The question is, how can you make it so? One technique is to follow a similar process as what’s outlined below:

ProcessFlowMobileApp

Most likely, your mobile application process will uniquely follow its own creative process path, but this example process makes a few considerations that your app can adopt to make it more reliable, fast, and fresh.
Note: The process in the grey box will happen at the same time (in parallel) as the other app-starting processes during the best and likely case scenarios.

  • Reliable: Your app is designed to work in any scenario (best, likely, and worse case scenarios).
    • Best case scenario: New data size is small/medium. Your device is fast. You connect to the external data easily and quickly so that the new data is ready before your app loads content on the screen. When content is loaded, it is the newest content.
    • Likely scenario: New data size is medium/large. Your device is fast enough to connect to the external data after the 2nd or 3rd attempt. Your app will have to load old content on the screen before it finishes downloading the new content, but at least the new content is loaded and the user is preoccupied with any content at all. If the user hits “refresh” the new content will show up, as desired.
    • Worst case scenario: New data size is large. Your device is slow. You fail to connect to external data because there is no internet connection or the device is just too slow. This is the first time the user ever used this app so there is no previously saved data.
      You need to have some locally stored data to use for the default content. This fallback data comes packaged with your app.
  • Fast: Even if the app is busy connecting with and downloading content, the app can load previous content or fallback content so that the download doesn’t have to finish before the user sees content on the screen.
  • Fresh: Even if new content fails to download the first time, the app will try multiple times to connect and download. This is important for mobile devices that contrast with laptops/desktops’ ability to, most likely, be able to connect and download external data on the first try.

Code Techniques

As mentioned above, this post focuses on mobile apps that use web technologies (Javascript / HTML 5) almost exclusively. So most of the advanced functionality has to be accomplished with Javascript. This “advanced functionality” required for a news app, like the one described by the data flow diagram, includes the following:

  • How can you connect with and download external data?
    • Only with Javascript and HTML5 technologies
  • How can you guarantee that you connect with new (non-cached) data?
    • Only with Javascript and HTML5 technologies
  • How do you parse discrete values, such as “title”, “description”, or “publish-date” once the data is downloaded?
    • Data format and Javascript’s ability to parse the data is important.
  • How can downloaded data be saved on your local mobile device so that it can be accessed later?
    • Only with Javascript and HTML5 technologies

How can you connect with and download external data?

First attempt: My initial attempt to connect with external data involved an AJAX call to an external file. Many issues arose with this technique, including the fact that it was difficult to ensure calls to external resources occurred in a specific synchronous order when AJAX is asynchronous, by nature. AJAX’s asynchronous behavior means that it occurs whenever it can, rather than when it is called in code. Also, AJAX calls seemed to occasionally fail, altogether. There had to be a more reliable, simpler method to call external data.

Success: Whenever you hit a wall trying to solve a problem, the best solution is usually the simplest.

Simplify. The solution was hidden in plain sight the whole time. I realized that it’s possible to link an external Javascript document to an HTML page so why can’t I generate all the external data for the application in one or more external .js files and then link them in the head of the app’s HTML page? This would prove to be a both elegant and reliable solution.


1.<script> src="EXTERNAL-DATA.js" </script>

Note: This technique assumes that you have control over the external data you need to connect to. For this project, a custom server-side application was written to read the external data (originally in XML format) and output a .js file, formatted to be consumed by the mobile application.

How can you guarantee that you connect with new (non-cached) data?

After implementing this technique, I soon discovered that data was failing to update. Reason: mobile devices sometimes cache external resources to increase speed of accessing these external resources. I needed a way to force the mobile device to always access a non-cached version EXTERNAL-DATA.js 100% of the time.

Success:
The best way to guarantee an external resource is not cached is to append a unique value (such as the current timestamp) at the end of the resource path. This causes the resource path to be recognized as unique and, therefore, not cached. But Javascript is a client-side language. Can you really use Javascript to generate an external resource link before that external resource is loaded into the document? You can. For example, you can do something similar to the following between the

< head>
tags of your .html document:


function addExternalScript(scriptSrc)

{

//generate a no cache query string value

var nocacheVal = ‘?nocache=’ + new Date().getTime();

//create script element

var allJsonScript = document.createElement(‘script’);

allJsonScript.setAttribute(‘type’,’text/javascript’);

allJsonScript.setAttribute(‘charset’,’utf-8′);

allJsonScript.setAttribute(‘src’, scriptSrc + nocacheVal);

//add the script as the first element of the head

var docHead = document.getElementsByTagName(“head”)[0];

docHead.insertBefore(allJsonScript, docHead.firstChild);

}

//add the external data script to the page

addExternalScript(“EXTERNAL-DATA.js”);

How do you parse discrete values, such as “title”, “description”, or “publish-date” once the data is downloaded?

When you design the contents of
EXTERNAL-DATA.js
a great data format to use is JSON (Javascript Object Notation). Javascript can easily interact with JSON objects. The following code is an example of JSON syntax and how to specific values can be accessed from a JSON object:

//JSON syntax example

var jsonObj = {“title”: “Breaking News – World peace is now a reality!”,

“summary”: “Governments, world leaders, and individuals spontaneously decided to…”};

//access a field value

var articleTitle = jsonObj.title;

//you can also use this syntax to access a field value

articleTitle = jsonObj[“title”];

Inside your
EXTERNAL-DATA.js
file, you can wrap your JSON value(s) inside a function that returns the JSON value(s). This will allow this function to be called inside your mobile app local script. Here is an example this
EXTERNAL-DATA.js
code:


function getExternalData()

{

var jsonObj = {“title”: “Breaking News – World peace is now a reality!”,

“summary”: “Governments, world leaders, and individuals spontaneously decided to…”};

return jsonObj;

}

Handling no/slow connection issues
: If your mobile app fails to connect with the external data, then any
getExternalData()
function call will throw a javascript error because this is an external script resource. Therefore, you could wrap your
getExternalData()
call in a javascript
try/catch statement
. If the
try/catch
throws an error, you can try again until you run out of retries or the
getExternalData()
function is successfully called.

How can downloaded data be saved on your local mobile device so that it can be accessed later?

HTML5/Javascript has many different special features that allow you to save data on your local device. Methods for saving include LocalStorage and the
File API
. You can find more documentation on different storage methods in the
storage section of the HTML5 Rocks site
.

Hopefully, this post has provided some helpful guidance and ideas. Good luck with your mobile project!

Picture of Paul Briscoe

Paul Briscoe

Share the Post:

Like what you’re reading?

Get access to our newsletter for occasional eCommerce news and insights. Opt out at any time by unsubscribing.