Tải bản đầy đủ (.pdf) (338 trang)

html5 iphone web application development

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (22.9 MB, 338 trang )

www.it-ebooks.info
HTML5 iPhone Web Application
Development
An introduction to web-application development for
mobile within the iOS Safari browser
Alvin Crespo
BIRMINGHAM - MUMBAI
www.it-ebooks.info
HTML5 iPhone Web Application Development
Copyright © 2013 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
First published: May 2013
Production Reference: 1170513
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84969-102-4
www.packtpub.com
Cover Image by Asher Wishkerman ()


www.it-ebooks.info
Credits
Author
Alvin Crespo
Reviewers
Dale Cruse
Faraz K. Kelhini
Acquisition Editor
Joanne Fitzpatrick
Lead Technical Editor
Neeshma Ramakrishnan
Technical Editors
Amit Ramadas
Neha Shanbhag
Project Coordinator
Arshad Sopariwala
Proofreaders
Paul Hindle
Chris Smith
Indexer
Rekha Nair
Graphics
Ronak Dhruv
Production Coordinator
Conidon Miranda
Cover Work
Conidon Miranda
www.it-ebooks.info
About the Author
Alvin Crespo is a creative technologist strongly focused on delivering compelling

user experiences through the use of frontend technologies. Utilizing the latest industry
standards, he strives to move the Web forward promoting open source technologies.
Having worked in startup and agency environments, he has helped build and architect
complex applications for both medium and large-sized companies.
First and foremost, I would like to thank my lovely wife, Janice
Smith, for helping me produce this book. This has only been possible
through the love and support you have given me. To my friends and
family who have been there throughout the process, my love and
endless thanks cannot express how awesome you all are.
www.it-ebooks.info
About the Reviewers
Dale Cruse is the co-author of HTML5 Multimedia Development Cookbook by Packt
Publishing and the technical editor of several other HTML5 books. He started his
career in 1995 as a U.S. Army photojournalist. Since making the switch to purely
digital at CBSNews.com, he's created web and mobile experiences for some of the
most well-known clients in the world, including 20th Century Fox, Bloomingdale's,
and MINI Cooper. Currently, he juggles being both a senior developer at Allen
& Gerritsen and being a New York Yankees fan in South Boston. An in-demand
speaker, you can't get him to shut up on Twitter at @dalecruse.
Faraz K. Kelhini has more than a decade of software development experience in
a broad range of disciplines. His core expertise and interest lies in web technologies,
including PHP (as well as frameworks like Symfony and Zend framework), Python,
HTML5, CSS3, JavaScript (as well as frameworks like jQuery and MooTools), and
Linux/Unix operating systems. He is a professional consultant, editor, and writer
who specializes in technical presentations, workshops, online content publishing, and
knowledge transfer. Faraz has more than 100 articles to his credit within prominent
publications such as Developer.com, .net magazine, and Smashing Magazine.
When not pursuing a new technology or idea, Faraz loves practicing his DSLR
photography skills. More information on his related writings, presentations,
and useful tools can be found at .

I would like to thank you, the reader; I hope that you enjoy this book
and produce a fantastic HTML5 iPhone App of your own. I look
forward to hearing your feedback and seeing what you come up
with! My thanks also go to my entire friends and family.
www.it-ebooks.info
www.PacktPub.com
Support les, eBooks, discount offers
and more
You might want to visit www.PacktPub.com for support les and downloads related to your
book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub les
available? You can upgrade to the eBook version at www.PacktPub.com and as a print book
customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@
packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range
of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
TM

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library.
Here, you can access, read and search across Packt's entire library of books.
Why Subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print and bookmark content
• On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib
today and view nine entirely free books. Simply use your login credentials for immediate access.
www.it-ebooks.info
Table of Contents
Preface 1

Chapter 1: Application Architecture 7
Implementing the HTML5 Mobile Boilerplate 8
Downloading and installing the HTML5 Mobile Boilerplate 8
Integrating the build script 9
Creating our application framework 9
Modifying the boilerplate 10
Customizing our markup 10
Customizing our framework 14
Creating semantic markup 18
Creating the header 18
Creating the footer 19
Clearing up section 20
Structuring our stylesheets 20
Global styling 21
Dening our global fonts 21
Our page layout 22
Using content with :before and :after 23
Styling our navigation 23
Responsive design principles 25
Media queries to the rescue 25
Responsive images 26
Fluid images 26
Establishing our JavaScript architecture 27
Structuring our app functionality 28
Namespacing our application 28
Immediately Invoked Function Expressions 28
www.it-ebooks.info
Table of Contents
[ ii ]
Use strict 29

Default options 29
Dening the constructor 30
The prototype 30
Dening public methods 32
Returning our constructor/function 33
Integrating a custom module template 34
Including our scripts 35
Initializing our framework 35
Routing to a mobile site 36
Redirecting via PHP 37
Redirecting via htaccess 37
Home screen icons 37
Introducing our build script 38
Conguring our build script 38
Minifying and concatenating scripts 38
Minifying and concatenating styles 39
Creating multiple environments 39
Navigating our directories 40
Building our project 40
Summary 42
Chapter 2: Integrating HTML5 Video 43
Conguring the server 43
Video formats 44
Video format directives 44
A simple HTML5 video 44
Single video format 45
Supporting multiple formats 45
Listening to HTML5 video events 46
Video markup review 47
Attaching video events 47

Initializing our video 51
Creating a JavaScript video library 52
Centralizing our events 53
Scope in JavaScript 54
Exposing functionality 55
Integrating callbacks 57
Extending callbacks 59
Using callbacks 59
Tying it all up 61
Customizing HTML5 video controls 64
Summary 70
www.it-ebooks.info
Table of Contents
[ iii ]
Chapter 3: HTML5 Audio 71
Server conguration 71
Audio formats 72
Audio format directives 72
Simple HTML5 audio integration 73
MediaElement abstraction 74
Creating App.MediaElement.js 74
Initializing App.MediaElement.js 76
Extending the MediaElement API for audio 77
The base template 77
Creating an instance of MediaElement 78
Finding and caching an audio element 78
Initializing MediaElement 78
Dynamic audio player 79
The select element 79
Switching audio tracks 81

The change event listener 81
The change event handler 82
Refactoring our code 84
Initializing our Audio class 85
Customizing HTML5 audio controls 86
Creating custom media controls 86
Adding interactivity to our customized controls 88
Sequential playback 88
The markup 89
The JavaScript 90
iOS considerations 93
Volume 93
Autoplay 93
Simultaneous playback 94
Summary 95
Chapter 4: Touch and Gestures 97
Simplifying the navigation 98
Navigation markup and styling 98
The basic template 98
Styling a select component 99
Navigation interactivity 99
The basic template 100
Caching our navigation 100
Listening and handling the change event 100
Initializing the navigation 101
www.it-ebooks.info
Table of Contents
[ iv ]
Touch and Gesture events 102
Touch events 102

On scroll 103
On touch and hold 103
On double-tap zoom 103
Supported touch events and how they work 103
Gestures 104
Creating a responsive photo gallery 105
Gallery markup and styling 106
The basic gallery slide list 106
Adding simple gallery controls 107
Making images responsive 107
Styling our gallery 108
Using CSS3 transitions 110
Gallery interactivity 111
The basic template 112
Caching the gallery 112
Connecting our controls 114
Gallery responsiveness 118
Extending the gallery for touch 123
The basic template 123
Default options and modularizing swipe events 124
Listening to touch events 125
Handling touch events 125
Putting it all together 127
The JavaScript 128
The markup 130
Summary 131
Chapter 5: Understanding HTML5 Forms 133
HTML5 input types 134
HTML5 attributes for forms 135
Form layout for iPhone 136

Sample HTML5 forms 137
Setup work 138
Including our forms styling 138
Updating the navigation 138
Including our navigation and forms scripts 139
The forms 139
The login form 139
The registration form 141
The prole form 144
Form validation 150
The basic template 150
Initializing our forms 151
www.it-ebooks.info
Table of Contents
[ v ]
Attaching events 152
Event handlers 152
Validating our input 153
Form styling for iOS 156
Basic styling 156
Custom styling 157
Summary 161
Chapter 6: Location-aware Applications 163
Geolocation specication 163
Implementation 164
Scope, security, and privacy 164
API descriptions 165
The Geolocation interface 166
The PositionOptions interface 167
The Position interface 169

The Coordinates interface 169
The PositionError interface 170
Use cases 171
Points of interest 172
Route navigation 172
Latest information 172
Google Maps API 173
The API(s) 173
Obtaining an API key 173
Activating the service 173
Retrieving the key 174
Geolocation and Google Maps 176
Markup preparation 176
The Geolocation wrapper 180
Geolocation with Google Maps 184
Summary 188
Chapter 7: One-page Applications 189
Model-View-Controller or MVC 189
Models 190
Views 190
Controllers 190
Relationships 190
Introduction to Underscore.js 191
Implementation 191
_.extend 192
_.each 193
_.template 194
www.it-ebooks.info
Table of Contents
[ vi ]

Introduction to Backbone.js 196
MVC and Backbone.js 196
Backbone models 196
Backbone views 199
Backbone collections 201
Server-side interactions 203
Our sample application 204
Application architecture 204
Basic sample architecture 205
Application markup 206
Application scripts 212
Summary 238
Chapter 8: Ofine Applications 239
Application Cache 239
The manifest le 240
Manifest implementation 241
A simple example 241
The markup 242
The JavaScript 243
Debugging the cache manifest 245
Debugging in the browser 246
Debugging using JavaScript 248
Handling ofine applications 249
A simple use case 249
Detecting network connectivity 250
The localStorage API 251
Summary 252
Chapter 9: Principles of Clean and Optimized Code 253
Optimizing stylesheets 254
Validating our CSS 254

W3C CSS Validator 254
Customizable options 256
Validating a successful example 257
Validating an unsuccessful example 258
CSS Lint 260
Customizable options 261
Proling our CSS 265
Optimizing our CSS 267
Avoid universal rules 267
Don't qualify ID or Class rules 268
Never use !important 268
Modularize styles 268
www.it-ebooks.info
Table of Contents
[ vii ]
Optimizing JavaScript 269
Validating JavaScript using JSLint 270
Validating a successful example using JSLint 271
Validating an unsuccessful example 272
Customizable options 274
Integrating JSLint 274
Proling our JavaScript 275
Optimizing our JavaScript 277
Avoid globals 277
Leave the DOM alone 278
Use literals 278
Modularize functionality 279
Summary 280
Chapter 10: Creating a Native iPhone Web Application 281
Setting up the development environment 282

Getting started with Xcode 282
Installing Xcode 282
Xcode IDE overview – the basics 282
Setting up PhoneGap 289
Installing PhoneGap 290
Creating a PhoneGap project 291
The PhoneGap license 292
Conguring our project 293
Transferring a web application 294
Transferring our assets 295
Including our markup 295
Incorporating our styles 298
Inserting our scripts 299
Debugging our application 303
Logging out our code 303
Using the Safari developer tools 304
Extending our application with native functionality 305
Conguring our application 306
Setting up our contacts functionality 306
Summary 311
Index 313
www.it-ebooks.info
www.it-ebooks.info
Preface
Web applications have come a long way since the 90s, where static HTML pages
were delivered to the client. In those days, web pages had a strict client-server
model, where much of the processing was done on the server and the client only
presented the information with little to no interaction. Such information was only
accessible through desktop computers on very slow networks.
Those days have passed, and we are now connected in ways that were impossible

before. From cellphones that can still make calls on the subway, to tablets presenting
the latest article from your favorite newspaper 30,000 feet in the air; we are now in
a digital age where information is easily accessible through innovative technologies.
Yet, we still struggle to create a seamless interaction between technology and the
physical world.
Although we have devices that are sensitive to our touch, can detect our location, and
have the ability to monitor our vital signals, it is still up to us to make applications that
will change the world. The hard work that goes into creating these applications usually
requires large teams, complex business roles, and costly expenses.
For a brief period of time, developing these applications presented a challenge to
many entrepreneurs who were looking to drive change. A staggered mobile market,
which continues to this day, contributed to limited development resources. What we
saw was an increase in the advancement of these technologies, but very few people
who understood or were even interested in learning all the languages felt
the necessity to create a cross-platform application.
However, it was only a matter of time until a single platform would arrive and
change the world forever. HTML5, and its implementation across devices, helped
drive the force necessary to deliver a platform that allowed developers to innovate
and change the world. Leveraging this technology in our applications allows us to
push the limit of the hardware while creating something that many users can enjoy,
no matter what device they prefer to use.
www.it-ebooks.info
Preface
[ 2 ]
Over the years, I have come to realize that device agnostic applications will
become the norm. We have seen competitors adopt these standards with little to no
impact on their success; in fact, it can be argued that it has done the opposite. For
these reasons, this book was written to provide you with the techniques to create
applications, based on open standards, and for the successful creation of device
agnostic software.

What this book covers
Chapter 1, Application Architecture, helps you to learn how to create a standard
architecture for iPhone web application development. We will customize the
standard HTML5 Mobile Boilerplate for our needs throughout the book.
Chapter 2, Integrating HTML5 Video, helps you to learn the basics of implementing
an HTML5 video player within your web application. We'll review the specication
and implement an exposed API to tap into.
Chapter 3, HTML5 Audio, explains an implementation of the HTML5 Audio API.
We'll create an audio player that utilizes the same principles from Chapter 2 to
create a reusable component.
Chapter 4, Touch and Gestures, helps you to learn about touch and gesture events,
including the similarities and differences. We'll go over a couple of examples and
more importantly, the specication to properly integrate our application's
user experience.
Chapter 5, Understanding HTML5 Forms, explains the new features in HTML5 forms,
ultimately understanding its uses for our iOS web applications. We'll review the new
inputs, their interactions, and the behaviors expected from the iOS operating system.
Chapter 6, Location-aware Applications, will have Geolocation as the key point, from the
specication to the full implementation in the Safari iOS browser. We'll create
an example that utilizes this feature and demonstrate how we can utilize it in our
own applications.
Chapter 7, One-page Applications, is jam-packed with information on how to create
a seamless experience in your application. We'll go over the principles of the MVC
design pattern and create an example that utilizes its full potential.
Chapter 8, Ofine Applications, will cover key topics such as Caching, History, and
local storage. The essentials will be covered and the details exposed in order for us
to create true ofine applications.
www.it-ebooks.info
Preface
[ 3 ]

Chapter 9, Principles of Clean and Optimized Code, will have us sidestepping the
development process to rene our craftsmanship. We'll go over best practices,
industry supported techniques, and ways to improve our code for the overall
benet of our applications.
Chapter 10, Creating a Native iPhone Web Application, reviews how we can create
the native application we have learned previously. Applying the same techniques
we'll create native applications based on open standards.
What you need for this book
This book aims to provide web application development solutions specically for
iOS. With that in mind, you will need an iPhone and/or iPad, preferably an Apple
computer with Mac OS X 10.8 and above. You will denitely need a text editor or
IDE of your choice, including Xcode 4 and above with the iOS simulator installed.
And ultimately, you'll be testing your applications in the most modern web
browsers, including Safari.
Who this book is for
This book is intended for beginner to intermediate level developers who are diving
into web application development specically for iOS. This book begins with
introductory level material, with each chapter advancing over each topic. The topics
covered will give you a good idea on how to approach the development process
and the steps needed to achieve those goals.
Conventions
In this book, you will nd a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and
an explanation of their meaning.
Code words in text are shown as follows: "Although we've written this code
previously, let's briey review the structure of the MediaElement class."
www.it-ebooks.info
Preface
[ 4 ]
A block of code is set as follows:

<div class="audio-container">
<audio controls preload>
<source src=" /assets/nintendo.mp3" type='audio/mpeg;
codecs="mp3"'/>
<p>Audio is not supported in your browser.</p>
</audio>
<select>
<option value="sample1.mp3" selected>Sample1</option>
<option value="sample2.mp3">Sample2</option>
<option value="sample3.mp3">Sample3</option>
</select>
</div>
New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "Then
download the zip le, by clicking on the Download as zip button."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for
us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to ,
and mention the book title via the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things
to help you to get the most from your purchase.
www.it-ebooks.info
Preface

[ 5 ]
Downloading the example code
You can download the example code les for all Packt books you have purchased
from your account at . If you purchased this book
elsewhere, you can visit and register to
have the les e-mailed directly to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you nd a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you would report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you nd any errata, please report them by visiting ktpub.
com/submit-errata, selecting your book, clicking on the errata submission form link,
and entering the details of your errata. Once your errata are veried, your submission
will be accepted and the errata will be uploaded on our website, or added to any list of
existing errata, under the Errata section of that title. Any existing errata can be viewed
by selecting your title from />Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works, in any form, on the Internet, please
provide us with the location address or website name immediately so that we
can pursue a remedy.
Please contact us at with a link to the suspected
pirated material.
We appreciate your help in protecting our authors, and our ability to bring
you valuable content.
Questions
You can contact us at if you are having a problem
with any aspect of the book, and we will do our best to address it.
www.it-ebooks.info

www.it-ebooks.info
Application Architecture
In this chapter, we will create a standard architecture for our iPhone application.
We will base it on the HTML5 Mobile Boilerplate and customize it for the needs
of the several projects in this book. From marking up our content in HTML5 to
creating a JavaScript framework, we'll create static pages that help us focus on
the foundations of iPhone Web Application development.
In this chapter, we will cover:
• Implementing the HTML5 Mobile Boilerplate
• Creating a preliminary architecture
• Customizing our framework
• Creating semantic markup
• Structuring our stylesheets
• Responsive design principles
• Establishing our JavaScript architecture
• Routing to a mobile site
• Home screen icons
• Introducing our build script
• Deploying our project
www.it-ebooks.info
Application Architecture
[ 8 ]
Implementing the HTML5 Mobile
Boilerplate
When you begin development, it is always critical to start with a basic framework
that can be molded to the needs of your project. In many cases, we develop these
frameworks in-house where we work, or perhaps for our own personal projects.
However, the open source community has presented us with a great framework we
can use in our projects—the HTML5 Mobile Boilerplate. This framework is based on
the well-known HTML5 Boilerplate, and has been optimized for mobile including a

lean HTML template; the utilization of Zepto, and use of tools and helpers optimized
for mobile.
Downloading and installing the HTML5 Mobile
Boilerplate
The rst step we need to take is to download the HTML5 Mobile Boilerplate,
which is located here:
/>Once the boilerplate is downloaded, you should see the following structure from
the unzipped archive le:
The Preliminary Directory Structure
www.it-ebooks.info
Chapter 1
[ 9 ]
The next step is to take these les and place them in the directory of your choice.
For example, I have placed my les in the following directory on my Mac:
/Users/alvincrespo/Sites/html5iphonewebapp
Next, we'll want to use a build system that helps us create multiple environments,
ease the deployment process, and overall make things easier when we want to
optimize our site for testing and/or production.
According to the documentation for the HTML5 Mobile Boilerplate, there are two
different types of build system, such as the Node Build script and the Ant Build
script. In this book, we'll be using the Ant Build script. I would recommend using
the Ant Build script since it has been around for a while and has the appropriate
features that I use in my projects, including CSS Split, which will help split up
the main CSS le that comes with the boilerplate.
Integrating the build script
To download the Ant Build script, go to the following link:
/>Then, download the zip le by clicking on the Download as zip button. When you
have downloaded the Ant Build script, copy the folder and its contents to your project.
Once your Ant Build script directory is fully transferred over to your project, rename
the directory containing the build script to build. At this point, you should have

your project completely set up for the rest of the applications in this book. We
will cover how to utilize the build script later on in this chapter.
Creating our application framework
With every project, it's important to create a framework that adjusts to your project's
needs. It's critical to think about every aspect of the project. From the required
document to the team's strengths and weaknesses, it's important we establish
a solid foundation that helps us build and adjust accordingly.
www.it-ebooks.info
Application Architecture
[ 10 ]
Modifying the boilerplate
We'll now modify our boilerplate for the needs of the projects we will be building.
For simplicity, we'll remove the following items from the folder:
• CHANGELOG.md
• crossdomain.xml
• README.md
• /doc (Directory)
Now that the directory has been cleaned up, it's time to take a look at some of
the boilerplate code and customize it for the needs of the projects in this book.
Customizing our markup
First, open up the application in your favorite text editor. Once we've opened up
the application in the editor of our choice, let's look at index.html.
The index le needs to be cleaned up in order to focus on iPhone Web Application
development, and also unused items such as Google Analytics need to be removed.
So let's remove some code that is not necessary for us.
Look for the following code:
<!DOCTYPE html>
<! [if IEMobile 7 ]> <html class="no-js iem7"> <![endif] >
<! [if (gt IEMobile 7)|!(IEMobile)]><! > <html class="no-js">
<! <![endif] >

Downloading the example code
You can download the example code les for all Packt books you
have purchased from your account at ktpub.
com. If you purchased this book elsewhere, you can visit http://
www.packtpub.com/support and register to have the les
e-mailed directly to you.
And modify it to this:
<!DOCTYPE html>
<html class="no-js">
www.it-ebooks.info

×