anatomy of an html 5 mobile web app
DESCRIPTION
Mobile applications Development - Lecture 8 Anatomy of an HTML 5 mobile web app PhoneGap This presentation has been developed in the context of the Mobile Applications Development course at the Computer Science Department of the University of L’Aquila (Italy). http://www.di.univaq.it/malavoltaTRANSCRIPT
Mobile Web AppsMobile Web AppsDevelopment
Ivano MalavoltaIvano Malavolta
http://www.di.univaq.it/malavolta
Roadmap
• Anatomy of a mobile web app• Anatomy of a mobile web app
• Classes of Mobile web apps
• PhoneGap
What is a Web App?
An application built with web technologies web technologies web technologies web technologies that is accessible via a mobile browser mobile browser mobile browser mobile browser and that is accessible via a mobile browser mobile browser mobile browser mobile browser and not exclusively through an app store
The browser may be either the standard device browser or an embedded browser (Hybrid app)browser or an embedded browser (Hybrid app)
Anatomy of a Web App
Anatomy of a mobile web app
This is why HTML5 Mobile Apps are hardhardhardhard!
In many cases you will need to createcreatecreatecreate every part of this diagram
If you don’t create it, you still need to testtesttesttest and If you don’t create it, you still need to testtesttesttest and debugdebugdebugdebug each piece
Setting up the Server
As usual, it all starts with an http http http http requestrequestrequestrequest
Then you need:• DataDataDataData• A A A A devicedevicedevicedevice detection detection detection detection mechanismmechanismmechanismmechanism [optional][optional][optional][optional]• The The The The appappappapp itselfitselfitselfitself
Data
Usually mobile apps do not talk directly withthe databasethe database� do not even think about JDBC, drivers, etc!
�They pass through an applicationapplicationapplicationapplication serverserverserverserver and communicate via:– standard HTTP requests for HTML content (eg PHP)– standard HTTP requests for HTML content (eg PHP)– REST-full services (XML, JSON, etc.)– SOAP
Data 2
• Data can be stored in any classical way:– Relational– Relational
– Graph
– Key-value
– Document-basedwww.parse.comwww.kinvey.com
LatestLatestLatestLatest trend: trend: trend: trend: backend-as-a-service– Data storage, users management, security,
big files storage, scalability, push notifications…
www.kinvey.com
BaaS
1. Developers build a visual model of their DBmodel of their DB
2. The service generates APIs and client-side libraries(compatible with iOS, Android, Windows Phone 7, etc.)
3. The data produced/consumed 3. The data produced/consumed in the app can be pushed/pulled to their DB
– Communication is handledvia REST or otherprotocols
Server-side device detection
All devices are unique
� you have to know on which device your app is running� you have to know on which device your app is running
� the app can adapt to the device capabilities
Many techniques, the most used are:• Andy Moore’s browser detector
– Works for PHP pages only– Works for PHP pages only
• Javascript
• External APIs– (DeviceAtlas, WURFL)
• CSS3 media queries
if (navigator.userAgent.match(/AppleWebKit/i) &&navigator.userAgent.match(/Mobile/i)) {
window.location.replace('/path/to/iphone/site/');
@media screen and (max-width: 980px) {}
The HTML5 app
Keep code very semanticKeep code very semanticKeep all the logic in JavascriptKeep (most of) the presentation in CSS3
Remember that the user may go offline• Offline data storage, cache manifest• Offline data storage, cache manifest
Progressive Progressive Progressive Progressive EnhancementEnhancementEnhancementEnhancement�Write all your markup first without any CSS or
JavascriptThe resulting markup should always be perfectly usable in its lowest form.
Progressive Enhancement
Key concept. GracefulGracefulGracefulGraceful degradationdegradationdegradationdegradation
Progressive Enhancement Techniques
• Always code your markup Always code your markup Always code your markup Always code your markup semanticallysemanticallysemanticallysemantically– ensure that the page is always usable, even with no stylesheetensure that the page is always usable, even with no stylesheet
• Have a device Have a device Have a device Have a device planplanplanplan– Know which device classes you intend to support before you
start to code• Have both your Have both your Have both your Have both your LCD and LCD and LCD and LCD and highhighhighhigh----end device designs before end device designs before end device designs before end device designs before
you begin to you begin to you begin to you begin to codecodecodecode– Try to visualize a way to create both versions from one code
base.Test on different mobile devices Test on different mobile devices Test on different mobile devices Test on different mobile devices from the beginning from the beginning from the beginning from the beginning • Test on different mobile devices Test on different mobile devices Test on different mobile devices Test on different mobile devices from the beginning from the beginning from the beginning from the beginning – your incremental work must display correctly in the intended
devices• If you plan to add a desktop layer, always create the If you plan to add a desktop layer, always create the If you plan to add a desktop layer, always create the If you plan to add a desktop layer, always create the
mobile version mobile version mobile version mobile version firstfirstfirstfirst
Anatomy of a Web App
Cache Manifest
ProblemProblemProblemProblem. Browsers have their own caches but theyare unreliable and heterogenousare unreliable and heterogenous
The Application Cache Application Cache Application Cache Application Cache allows a developer to specify which files the browser should cache and make available to offline users
CACHE MANIFEST CACHE MANIFEST /main/features.js /main/settings/index.css http://files/images/scene.jpg http://files/images/world.jpg
Cache Manifest
A cache manifest gives you the following benefits:• Offline browsing Offline browsing Offline browsing Offline browsing
users can navigate your full site when they're offline– users can navigate your full site when they're offline• Speed Speed Speed Speed
– cached resources are local, and therefore load faster• Reduced server loadReduced server loadReduced server loadReduced server load
– the browser will only download resources from the server that have changed
This solution does not cover dynamic data cachingIn that case you can use javascript to get your data
Javascript
Hybrid Scripts
These scripts bridge the gap between your These scripts bridge the gap between your These scripts bridge the gap between your These scripts bridge the gap between your core scripts and the devicecore scripts and the devicecore scripts and the devicecore scripts and the device SDKSDKSDKSDKcore scripts and the devicecore scripts and the devicecore scripts and the devicecore scripts and the device SDKSDKSDKSDK
– A necessary step if you plan to ship your HTML5 app in a native wrapper like a standard iOSUIWebView or Cordova
– They may need to be distinct for each platform you plan to support
• For example, the cordova.js file for Android is subtlydifferent from the iOS’s one
Core Scripts
The The The The common components of your app common components of your app common components of your app common components of your app
– they implement the internal logic that your app will require to assemble and render your HTML5 pages
– they will be the same in every platform
– examples of duties:• REST API access• REST API access
• Domain entities representation
• …
– they include also JS libraries like JQuery and othermicroframeworks
Device Scripts
They work They work They work They work to emulate native behaviors of the to emulate native behaviors of the to emulate native behaviors of the to emulate native behaviors of the device with device with device with device with JavascriptJavascriptJavascriptJavascriptdevice with device with device with device with JavascriptJavascriptJavascriptJavascript
– these scripts may be unique to each platform you plan to support
– examples:• JQueryMobile (JS part)• JQueryMobile (JS part)• JQTouch (JS part)• SenchaTouch (JS part)• iui-js
A note on Mobile Web Frameworks
Frameworks like JQueryMobile, JQTouch are usefulsince they give you the standard visual standard visual standard visual standard visual language language language language since they give you the standard visual standard visual standard visual standard visual language language language language the user is accustom to out-of-the-box
However, evaluate carefully what framework you need, you may have issuesissuesissuesissues about:
– performance (the UI may get slow)– performance (the UI may get slow)
– stability, debuggability
– customization problems (you may be forced in doingeverything the framework-way)
– your app may look like many others
CSS3
Device Themes
TheTheTheThe presentation elements that presentation elements that presentation elements that presentation elements that will be will be will be will be required to mimic the platform required to mimic the platform required to mimic the platform required to mimic the platform aestheticaestheticaestheticaestheticrequired to mimic the platform required to mimic the platform required to mimic the platform required to mimic the platform aestheticaestheticaestheticaesthetic
– it may be unique to each platform you plan to support
– examples:– examples:• Sencha Touch (CSS)
• JQueryMobile (CSS)
• …
Core Themes
The presentation elements you use The presentation elements you use The presentation elements you use The presentation elements you use independently from the app and platformindependently from the app and platformindependently from the app and platformindependently from the app and platformindependently from the app and platformindependently from the app and platformindependently from the app and platformindependently from the app and platform
– Keep presentation presentation presentation presentation essentials essentials essentials essentials as a unique stylesheetthat will serve as your core theme
– They are the elements that should always be the same regardless of what platform you use
– Examples:– Examples:• Resets• Toolbar colors• Layouts• Typography• …
App Themes
The The The The presentation presentation presentation presentation elements that are specific to elements that are specific to elements that are specific to elements that are specific to your appyour appyour appyour appyour appyour appyour appyour app
– Basically, they are similar to a core theme, but theyare specific to an app
– Examples:• Logos• Logos• Toolbar colors• Layouts• Typography• …
Roadmap
• Anatomy of a mobile web app• Anatomy of a mobile web app
• Classes of Mobile web apps
• PhoneGap
Classes of Mobile Web Apps
A mobile web app will always be limited to the capabilities of the browser browser browser browser and device and device and device and device capabilities of the browser browser browser browser and device and device and device and device available available available available
This environment cannot be assured at the time of development
The following classes classes classes classes of development of development of development of development can help to prioritize design and development effort
Class 1
It uses the latest innovations and capabilities present only in the iPhoneiPhoneiPhoneiPhone (3GS and higher, iPod touch 4th only in the iPhoneiPhoneiPhoneiPhone (3GS and higher, iPod touch 4th Gen, iPad) and Android 4.0Android 4.0Android 4.0Android 4.0
Examples:
Facebook for iPhone
Flipboard for iPhoneFlipboard for iPhone
Class 1
AdvantagesAdvantagesAdvantagesAdvantages• Best possible mobile experience• Complex user interfaces, animations is possible• Complex user interfaces, animations is possible• Limited access to device features is possible• The user experience can be very close, and in some
cases on par with native iPhone apps• Fixed headers and footers are possible with Javascript
DisadvantagesDisadvantagesDisadvantagesDisadvantages• They do do do do notnotnotnot have backward compatibility and do do do do
notnotnotnot support other platforms• Complex Javascript is required for data integration
and is difficult to debug
Class 2
It supports highhighhighhigh----end end end end WebKitWebKitWebKitWebKit browsers browsers browsers browsers with devices that have at least 1Ghz processorsthat have at least 1Ghz processors
It supports all iOS devices,
2.2+ Android devices, WP 7.5
Example:
Instagram for Android 2.3
Class 2
AdvantagesAdvantagesAdvantagesAdvantages• Complex user interfaces are possible• Complex user interfaces are possible• Support the majority of high-end smartphones on the
marketplace• Has limited backward compatibility
DisadvantagesDisadvantagesDisadvantagesDisadvantages• Use of animationsanimationsanimationsanimations are processor and battery intensive • Use of animationsanimationsanimationsanimations are processor and battery intensive
(Javascript-based animation needs to be used instead of CSS, or animations need to be omitted altogether)
• Cannot use fixed footers and headers• Complex javascript can be required for data integration
and is difficult to debug
Class 3
It has the highest degree of smartphone device highest degree of smartphone device highest degree of smartphone device highest degree of smartphone device compatibilitycompatibilitycompatibilitycompatibility, provides high quality user experience, compatibilitycompatibilitycompatibilitycompatibility, provides high quality user experience, as well as supporting higher and lower classes
It supports all iOS devices, all Android devices, WP BlackBerry Torch
Class 3
AdvantagesAdvantagesAdvantagesAdvantages
• Supports the majority of devices, but not all• Supports the majority of devices, but not all
• Provides a quality user experience on more capable browsers, and degrades to lessor devices
DisadvantagesDisadvantagesDisadvantagesDisadvantages
• Cannot support animations or screen transitions• Cannot support animations or screen transitions
• Cannot support fixed header or footer
• Limited javascript support
Class 4
It is designed with compatibilitycompatibilitycompatibilitycompatibility in mind, seeking to have the best possible user experience across the have the best possible user experience across the widest number of devices
Any mobile web app looking to have the maximum cross platform supportcross platform supportcross platform supportcross platform support, should look no further than a Class 4 experiencethan a Class 4 experience
It is more website than web app
Class 4
AdvantagesAdvantagesAdvantagesAdvantages
• Support the largest number of handsets• Support the largest number of handsets
• Is simple to design and develop
• Is simple to deploy
DisadvantagesDisadvantagesDisadvantagesDisadvantagesDisadvantagesDisadvantagesDisadvantagesDisadvantages
• Requires significant Quality Assurance time
Universal App
It is an experience that is built for multiple device built for multiple device built for multiple device built for multiple device contextscontextscontextscontexts, but with a single source of contentcontextscontextscontextscontexts, but with a single source of content
Sometimes referred to as Responsive Responsive Responsive Responsive Web DesignWeb DesignWeb DesignWeb Design
Warning. Warning. Warning. Warning. In this case the user experience is driven by technological constraints, not user needsby technological constraints, not user needs
Warning.Warning.Warning.Warning. This approach is something that has proven unsuccessful with most mobile platforms and applications
Universal App
AdvantagesAdvantagesAdvantagesAdvantages• Support mobile devices from a single code base• Based in web standards• Based in web standards• Increases accessibility and Search Engine Optimization
(SEO)• Data integration is very simple
DisadvantagesDisadvantagesDisadvantagesDisadvantages• Must be designed for maximum device compatibility • Must be designed for maximum device compatibility
(Lower Common Denominator or LCD-based Design)• Does not address the users context• Most websites are not designed to be “universal” and
need to be refactored from scratch
Browsers Classes
We can look at mobile experiences also w.r.t. the browsersbrowsersbrowsersbrowsers capabilitiescapabilitiescapabilitiescapabilitiesbrowsersbrowsersbrowsersbrowsers capabilitiescapabilitiescapabilitiescapabilities
Roadmap
• Anatomy of a mobile web app• Anatomy of a mobile web app
• Classes of Mobile web apps
• PhoneGap
PhoneGap
• Conceptual Overview
• Phonegap Development Guidelines• Phonegap Development Guidelines
PhoneGap VS Cordova
Adobe/Nitobi donated the PhoneGap codebase to the Apache foundation
Phonegap is a Apache foundation– wider audience and contributors– Transparent governance
• Better documentation
– Easier contributions for companies• Apache Licensing
Phonegap is a distribution ofApache Cordova
�There was only one problem: trademark trademark trademark trademark ambiguityambiguityambiguityambiguity
� CORDOVACORDOVACORDOVACORDOVA
PhoneGap
The UI layer is a web browser web browser web browser web browser viewviewviewview– 100% width– 100% width
– 100% height
Headless web browser– No URL bar
– No chrome
This is a web browser instance
– No chrome
– No window decorations
– No zooming
– No text selection
PhoneGap
You develop your app using
• HTML• HTML
• CSS
• Javascript
You use the same web view same web view same web view same web view of the native OSof the native OSof the native OSof the native OS
– iOS = UIWebView
– Android = android.webkit.WebView
PhoneGap API
Allows you to access native OS functionality using JavaScript
� you develop your app using web technologies and PhoneGap handles communication with the native OS
http://bit.ly/HBPPY5
PhoneGap API
WebView app
PhoneGapJavascript
API provider for Android
API provider for iOS
API provider for Windows for Windows
Phone
API provider for
Blacberry
PhoneGap
PhoneGap API
PhoneGap API on iOS - general idea
1. the native web views have events/notifications whenever the url/address is changedthe url/address is changed
2. cordova.js parses messages into strings and puts them as the source URL inside a hidden IFrame element
3. This navigation action is intercepted on the native layer and converted to a native object, and the default navigation action is blockednavigation action is blocked
4. The string is parsed and a native code operation is performed
5. The native layer writes back to the web view layer by executing javascript strings
Recurrent App Architecture
The appappappapp acts as a client for user interaction
The app communicates with an application server application server application server application server to The app communicates with an application server application server application server application server to receive data
The application server handles business logic and communicates with a backbackbackback----end data end data end data end data repositoryrepositoryrepositoryrepository
http://bit.ly/HBPPY5
The App
It generally uses the singlesinglesinglesingle----page page page page application application application application modelmodelmodelmodel• the application logic is inside a single HTML single HTML single HTML single HTML pagepagepagepagethe application logic is inside a single HTML single HTML single HTML single HTML pagepagepagepage
• This page is never unloaded from never unloaded from never unloaded from never unloaded from memorymemorymemorymemory
• Data will be displayed by updating the HTML updating the HTML updating the HTML updating the HTML DOMDOMDOMDOM
• Ex. Using JQuery
• data is retrieved from the application server using AJAXAJAXAJAXAJAX
The Application Server
It is a classical web server– serverserverserverserver----side side side side scripting language scripting language scripting language scripting language such as Java, .NET, PHP, etc…
– communication can be based on:
• standard HTTP requests for HTML content
• REST-ful services (XML, JSON, etc.)
• SOAP
– It performs business business business business logiclogiclogiclogic, and generally gets or pushes data from a separate data repository
The Back-end Repository
It may be:– a standard DB standard DB standard DB standard DB (usually deployed in the same machine of
the application server)the application server)– an externalexternalexternalexternal API API API API (see www.programmableweb.com)
Both application server and back-end repository can beprovided as a service � BaaSBaaSBaaSBaaS
Features Coverage
PhoneGap Plugins
Sometimes PhoneGap is not enough as is for our purposes
• Unsupported feature• Unsupported feature
• heavyweight data processing is faster in native code– ex. images manipulation
• background processing is better handled natively– ex. Files sync
• complex business logic
� You need to develop a PhoneGapPhoneGapPhoneGapPhoneGap pluginpluginpluginplugin
http://wiki.phonegap.com/w/page/36752779/PhoneGap%20Plugins
PhoneGap Plugins
PurposePurposePurposePurpose.... To expose a Phone native functionality to thebrowserbrowser
This is done by developing– a Custom Native Custom Native Custom Native Custom Native ComponentComponentComponentComponent
Different for each platform
– a Custom Custom Custom Custom JavascriptJavascriptJavascriptJavascript APIAPIAPIAPI– a Custom Custom Custom Custom JavascriptJavascriptJavascriptJavascript APIAPIAPIAPIIt should be always the same
PhoneGap Plugins
PhoneGap
• Conceptual Overview
• Phonegap Development Guidelines• Phonegap Development Guidelines
Project Structure
If your app gets complex, you mayprefer to use the structureprefer to use the structurepresented in the AnatomyAnatomyAnatomyAnatomy ofofofof a a a a HTML5 web HTML5 web HTML5 web HTML5 web appappappapp part of thislecture
Page Structure
• Place all CSS stylesheets at the at the at the at the beginningbeginningbeginningbeginning• Place all CSS stylesheets at the at the at the at the beginningbeginningbeginningbeginning– allows the page to render progressively
– avoids flickering
• Place all JS scripts that do not affect page layout at the endat the endat the endat the endat the endat the endat the endat the end– every script must be parsed before it can be used
– they block parallel downloads
Images and Style
• First of all, avoid images when possible
– you may use CSS gradiends, effects, etc.– you may use CSS gradiends, effects, etc.
• Try to avoid advanced CSS properties
– for example, text-shadow and box-shadow, opacity
• Use touch events, instead of onClick
– onClick may take up to 500ms to execute!
Text Management
• If the input is numeric, open up only the numeric keyboard– The same holds for email, websites, ecc.– The same holds for email, websites, ecc.
<input type="text" pattern="[0-9]*" value="numeric"value="numeric"value="numeric"value="numeric" />
• Disable user selection
<style><style>* {-webkit-touch-callout: none;-webkit-user-select: none;}</style>
CSS Hardware Acceleration
When you use
----webkitwebkitwebkitwebkit----transformtransformtransformtransform----webkitwebkitwebkitwebkit----transformtransformtransformtransform
you have to use
translate3d(translate3d(translate3d(translate3d(x,y,zx,y,zx,y,zx,y,z))))
instead of using
translate(x,y)translate(x,y)
In iOS, the last instruction is not HW-accelerated
Scrolling
I you want to scroll only a portion of your view, youshould use this libraryshould use this library
http://cubiq.org/iscroll
Examples:
– fixed header and footer, with scrollable content
– scrollable sub-views with fixed description below
Frameworks
JQueryMobile, JQuery, Backbone, etc. are beautiful tools…tools…
However they may impact the performanceperformanceperformanceperformance of your app
�Use a framework only when it is necessary– Don’t use JQuery only because of the $() syntax!
SolutionSolutionSolutionSolution• build your own micro-framework• cut out PhoneGap plugins you do not use• use micro-frameworks (http://microjs.com)
References
http://www.tricedesigns.com/
http://pinchzoom.com/
http://hiediutley.com/
Chapters 11-12