How It Works: the HTML5 Application Cache Offline Web Applications work by leveraging what is known as the application cache.. The application cache can store your entire website offline
Trang 1Now, let’s return to ourdisplayOnMapfunction and deal with the nitty-gritty ofactually displaying the map First, we’ll create amyOptionsvariable to store some
of the options that we’ll pass to the Google Map:
js/geolocation.js (excerpt)
function displayOnMap(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
// Let’s use Google Maps to display the location
The second option we’ll set is the kind of map we want to display We can choosefrom the following:
Options in Google Maps
To learn more about Google Maps’ options, see the Map Options section of the Google Maps tutorial.5
5 http://code.google.com/apis/maps/documentation/javascript/tutorial.html#MapOptions
Trang 2Now that we’ve set our options, it’s time to create our map! We do this by creating
a new Google Maps object withnew google.maps.Map()
The first parameter we pass is the result of the DOM methodgetElementById, which
we use to grab the placeholderdivwe put in ourindex.htmlpage Passing the results
of this method into the new Google Map means that the map created will be placedinside that element
The second parameter we pass is the collection of options we just set We store theresulting Google Maps object in a variable calledmap:
js/geolocation.js (excerpt)
function displayOnMap(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
// Let’s use Google Maps to display the location
Now that we have a map, let’s add a marker with the location we found for the user
A marker is the little red drop we see on Google Maps that marks our location
In order to create a new Google Maps marker object, we need to pass it another kind
of object: agoogle.maps.LatLngobject—which is just a container for a latitude andlongitude The first new line creates this by callingnew google.maps.LatLngandpassing it thelatitudeandlongitudevariables as parameters
Now that we have agoogle.maps.LatLngobject, we can create a marker We call
new google.maps.Marker, and then between two curly braces ({}) we setposition
to theLatLngobject,mapto the map object, andtitleto"Hello World!" The title
is what will display when we hover our mouse over the marker:
Trang 3js/geolocation.js (excerpt)
function displayOnMap(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
You can find a plethora of documentation about Google Maps’ JavaScript API, version
3 in the online documentation.6
A Final Word on Older Mobile Devices
While the W3C Geolocation API is well-supported in current mobile device browsers,you may need to account for older mobile devices, and support all the geolocationAPIs available If this is the case, you should take a look at the open source librarygeo-location-javascript.7
6 http://code.google.com/apis/maps/documentation/javascript/
7 http://code.google.com/p/geo-location-javascript/
Trang 4Offline Web Applications
The visitors to our websites are increasingly on the go With many using mobile
devices all the time, it’s unwise to assume that our visitors will always have a liveinternet connection Wouldn’t it be nice for our visitors to browse our site or use
our web application even if they’re offline? Thankfully, we can, with Offline Web
as Gmail; wouldn’t it be useful to be able to compose drafts in the app while you
were on the subway traveling to work? What about online to-do lists, contact agers, or office applications? These are all examples of applications that benefit
man-from being online, but which we’d like to continue using if our internet connectioncuts out in a tunnel
The Offline Web Applications spec is supported in:
It is currently unsupported in all versions of IE
How It Works: the HTML5 Application Cache
Offline Web Applications work by leveraging what is known as the application
cache The application cache can store your entire website offline: all the JavaScript,
HTML, and CSS, as well as all your images and resources
This sounds great, but you may be wondering, what happens when there’s a change?That’s the beauty of the application cache: your application is automatically updatedevery time the user visits your page while online If even one byte of data has
changed in one of your files, the application cache will reload that file
Trang 5Application Cache versus Browser Cache
Browsers maintain their own caches in order to speed up the loading of websites; however, these caches are only used to avoid having to reload a given file—and not in the absence of an internet connection Even all the files for a page are cached
by the browser If you try to click on a link while your internet connection is down, you’ll receive an error message.
With Offline Web Applications, we have the power to tell the browser which files should be cached or fetched from the network, and what we should fall back to
in the event that caching fails It gives us far more control about how our websites are cached.
Setting Up Your Site to Work Offline
There are three steps to making an Offline Web Application:
1 Create acache.manifestfile
2 Ensure that the manifest file is served with the correct content type
3 Point all your HTML files to thecache manifest
The HTML5 Herald isn’t really an application at all, so it’s not the sort of site for
which you’d want to provide offline functionality Yet it’s simple enough to do,and there’s no real downside, so we’ll go through the steps of making it availableoffline to illustrate how it’s done
The cache.manifest File
Despite its fancy name, thecache.manifestfile is really nothing more than a text filethat adheres to a certain format
Here’s an example of a simplecache.manifestfile:
Trang 6*
The first line of thecache.manifestfile must readCACHE MANIFEST After this line,
we enterCACHE:, and then list all the files we’d like to store on our visitor’s hard
drive ThisCACHE:section is also known as the explicit section (since we’re explicitlytelling the browser to cache these files)
Upon first visiting a page with acache.manifestfile, the visitor’s browser makes a
local copy of all files defined in the section On subsequent visits, the browser willload the local copies of the files
After listing all the files we’d like to be stored offline, we can specify an online
whitelist Here, we define any files that should never be stored offline—usually
because they require internet access for their content to be meaningful For example,you may have a PHP script,lastTenTweets.php, that grabs your last ten updates fromTwitter and displays them on an HTML page The script would only be able to pullyour last ten tweets while online, so it makes no sense to store the page offline
The first line of this section is the wordNETWORK Any files specified in theNETWORKsection will always be reloaded when the user is online, and will never be availableoffline
Here’s what that example online whitelist section would look like:
NETWORK
lastTenTweets.php
Unlike the explicit section, where we had to painstakingly list every file we wanted
to store offline, in the online whitelist section we can use a shortcut: the wildcard
* This asterisk tells the browser that any files or URLs not mentioned in the explicitsection (and therefore not stored in the application cache) should be fetched from
the server
Here’s an example of an online whitelist section that uses the wildcard:
NETWORK
*
Trang 7All Accounted For
Every URL in your website must be accounted for in thecache.manifestfile, even URLs that you simply link to If it’s unaccounted for in the manifest file, that re- source or URL will fail to load, even if you’re online To avoid this problem, you should use the * in the NETWORK section.
You can also add comments to yourcache.manifestfile by beginning a line with#.Everything after the#will be ignored Be careful to avoid having a comment as thefirst line of yourcache.manifestfile—as we mentioned earlier, the first line must beCACHE MANIFEST You can, however, add comments to any other line
It’s good practice to have a comment with the version number of yourcache.manifest
file (we’ll see why a bit later on):
Setting the Content Type on Your Server
The next step in making your site available offline is to ensure that your server isconfigured to serve the manifest files correctly This is done by setting the contenttype provided by your server along with thecache.manifestfile—we discussed contenttype in the section called “MIME Types” in Chapter 5, so you can skip back therenow if you need a refresher
Assuming you’re using the Apache web server, add the following to your.htaccess
file:
AddType text/cache-manifest manifest
Trang 8Pointing Your HTML to the Manifest File
The final step to making your website available offline is to point your HTML pages
to the manifest file We do that by setting themanifestattribute on thehtmlelement
in each of our pages:
Do This for Every Page
Each HTML page on your website must set the manifest attribute on the html
element Ensure you do this, or your application might not be stored in the
applic-ation cache! While it’s true that you should only have onecache.manifestfile for
the entire application, every HTML page of your web application needs <html
manifest="/cache.manifest">.
Getting Permission to Store the Site Offline
As with geolocation, browsers provide a permission prompt when a website is using
acache.manifestfile Unlike geolocation, however, not all browsers are required to
do this When present, the prompt asks the user to confirm that they’d like the
website to be available offline Figure 10.3 shows the prompt’s appearance in Firefox
Figure 10.3 Prompt to allow offline web application storage in the app cache
Going Offline to Test
Once we have completed all three steps to make an offline website, we can test outour page by going offline Firefox and Opera provide a menu option that lets you
work offline, so there’s no need to cut your internet connection To do that in Firefox,
go toFile>Work Offline, as shown in Figure 10.4
Trang 9Figure 10.4 Testing offline web applications with Firefox’s Work Offline modeWhile it’s convenient to go offline from the browser menu, it’s most ideal to turnoff your network connection altogether when testing Offline Web Applications.
Testing If the Application Cache Is Storing Your Site
Going offline is a good way to spot-check if our application cache is working, butfor more in-depth debugging, we’ll need a finer instrument Fortunately, Chrome’sWeb Inspector tool has some great features for examining the application cache
To check if ourcache.manifestfile has the correct content type, here are the steps tofollow in Chrome (http://html5laboratory.com/s/offline-application-cache.html has
a sample you can use to follow along):
1 Navigate to the URL of your home page in Chrome
2 Open up the Web Inspector (click the wrench icon, then chooseTools>Developer Tools)
3 Click on theConsoletab, and look for any errors that may be relevant to the
cache.manifestfile If everything is working well, you should see a line thatstarts with “Document loaded from Application Cache with manifest” and ends
Trang 10with the path to yourcache.manifestfile If you have any errors, they will show
up in theConsole, so be on the lookout for errors or warnings here
4 Click on theResourcestab
5 Expand theApplication Cachesection Your domain (www.html5laboratory.com
in our example) should be listed
6 Click on your domain Listed on the right should be all the resources stored inChrome’s application cache, as shown in Figure 10.5
Figure 10.5 Viewing what is stored in Chrome’s Application Cache
Making The HTML5 Herald Available Offline
Now that we understand the ingredients required to make a website available offline,
let’s practice what we’ve learned on The HTML5 Herald The first step is to create
ourcache.manifestfile You can use a program like TextEdit on the Mac or Notepad
on Windows to create it, but you have to make sure the file is formatted as plain
text If you’re using Windows, you’re in luck! As long as you use Notepad to createthis file, it will already be formatted as plain text To format a file as plain text in
TextEdit on the Mac, chooseFormat>Make Plain Text Start off your file by includingthe lineCACHE MANIFESTat the top
Next, we need to add all the resources we’d like to be available offline in the explicitsection, which starts with the wordCACHE: We must list all our files in this section
Since there’s nothing on the site that requires network access (well, there’s one
Trang 11thing, but we’ll get to that in a bit), we’ll just add an asterisk to theNETWORKsection
to catch any files we may have missed in the explicit section
Here’s an excerpt from ourcache.manifestfile:
And we’re set! We can now browse The HTML5 Herald at our leisure, whether we
have an internet connection or not
Trang 12Limits to Offline Web Application Storage
While the Offline Web Applications spec doesn’t define a specific storage limit forthe application cache, it does state that browsers should create and enforce a storagelimit As a general rule, it’s a good idea to assume that you’ve no more than 5MB
of space to work with
Several of the files we specified to be stored offline are video files Depending on
how large your video files are, it mightn’t make any sense to have them available
offline, as they could exceed the browser’s storage limit
What can we do in that case? We could place large video files in theNETWORKsection,but then our users will simply see an unpleasant error when the browser tries to
pull the video while offline
A better alternative is to use an optional section of thecache.manifestfile: the fallbacksection
The Fallback Section
This section allows us to define what the user will see should a resource fail to load
In the case of The HTML5 Herald, rather than storing our video file offline and
placing it in the explicit section, it makes more sense to leverage the fallback section.Each line in the fallback section requires two entries The first is the file for whichyou want to provide fallback content You can specify either a specific file, or a
partial path like media/, which would refer to any file located in themediafolder
The second entry is what you would like to display in case the file specified fails
Trang 13Of course, this is a bit redundant since, as you know from Chapter 5, the HTML5videoelement already includes a fallback image to be displayed in case the videofails to load.
So, for some more practice with this concept, let’s add another fallback In the eventthat any of our pages don’t load, it would be nice to define a fallback file that tellsyou the site is offline We can create a simpleoffline.htmlfile:
<title>We are offline!</title>
<link rel="stylesheet" href="css/styles.css?v=1.0"/>
cache.manifest (excerpt)
FALLBACK:
media/ images/video-fallback.jpg
/ /offline.html
Safari Offline Application Cache Fails to Load Media Files
There is currently a bug in Safari 5 where media files such as.mp3and.mp4won’t load from the offline application cache.