Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
143023864X_HT5.pdf
Скачиваний:
8
Добавлен:
21.02.2016
Размер:
7.98 Mб
Скачать

CHAPTER 12 CREATING OFFLINE WEB APPLICATIONS

<link rel="stylesheet" href="html5.css"> </head>

<body>

<header>

<h1>Offline Example</h1> </header>

<section>

<article>

<button id="installButton">Check for Updates</button> <h3>Log</h3>

<div id="info"> </div>

</article>

</section>

</body>

</html>

There are a couple of things to note in this HTML that pertain to this application's offline capabilities. The first is the manifest attribute on the HTML element. Most of the HTML examples in this book omit the <html> element because it is optional in HTML5. However, the ability to cache offline depends on specifying the manifest file there.

The second thing to note is the button. That will give the user control over configuring this application for offline use.

Creating the Offline JavaScript

For this example, the JavaScript is contained in multiple .js files included with <script> tags. These scripts are cached along with the HTML and CSS.

<offline.js>

/*

* log each of the events fired by window.applicationCache */

window.applicationCache.onchecking = function(e) { log("Checking for application update");

}

window.applicationCache.onnoupdate = function(e) { log("No application update found");

}

window.applicationCache.onupdateready = function(e) { log("Application update ready");

}

window.applicationCache.onobsolete = function(e) { log("Application obsolete");

}

window.applicationCache.ondownloading = function(e) {

307

CHAPTER 12 CREATING OFFLINE WEB APPLICATIONS

log("Downloading application update");

}

window.applicationCache.oncached = function(e) { log("Application cached");

}

window.applicationCache.onerror = function(e) { log("Application cache error");

}

window.addEventListener("online", function(e) { log("Online");

}, true);

window.addEventListener("offline", function(e) { log("Offline");

}, true);

/*

* Convert applicationCache status codes into messages */

showCacheStatus = function(n) {

statusMessages = ["Uncached","Idle","Checking","Downloading","Update Ready","Obsolete"]; return statusMessages[n];

}

install = function() { log("Checking for updates"); try {

window.applicationCache.update(); } catch (e) {

applicationCache.onerror();

}

}

onload = function(e) {

// Check for required browser features if (!window.applicationCache) {

log("HTML5 Offline Applications are not supported in your browser."); return;

}

if (!navigator.geolocation) {

log("HTML5 Geolocation is not supported in your browser."); return;

}

if (!window.localStorage) {

log("HTML5 Local Storage not supported in your browser."); return;

308

CHAPTER 12 CREATING OFFLINE WEB APPLICATIONS

}

log("Initial cache status: " + showCacheStatus(window.applicationCache.status)); document.getElementById("installButton").onclick = checkFor;

}

<log.js>

log = function() {

var p = document.createElement("p");

var message = Array.prototype.join.call(arguments, " "); p.innerHTML = message; document.getElementById("info").appendChild(p);

}

Check for ApplicationCache Support

In addition to the offline application cache, this example uses geolocation and local storage. We ensure that the browser supports all of these features when the page loads.

onload = function(e) {

// Check for required browser features if (!window.applicationCache) {

log("HTML5 Offline Applications are not supported in your browser."); return;

}

if (!navigator.geolocation) {

log("HTML5 Geolocation is not supported in your browser."); return;

}

if (!window.localStorage) {

log("HTML5 Local Storage is not supported in your browser."); return;

}

if (!window.WebSocket) {

log("HTML5 WebSocket is not supported in your browser."); return;

}

log("Initial cache status: " + showCacheStatus(window.applicationCache.status)); document.getElementById("installButton").onclick = install;

}

Adding the Update Button Handler

Next, add an update handler that updates the application cache as follows:

install = function() { log("Checking for updates"); try {

window.applicationCache.update();

309

CHAPTER 12 CREATING OFFLINE WEB APPLICATIONS

} catch (e) { applicationCache.onerror();

}

}

Clicking this button will explicitly start the cache check that will cause all cache resources to be downloaded if necessary. When available updates have completely downloaded, a message is logged in the UI. At this point, the user knows that the application has successfully installed and can be run in offline mode.

Add Geolocation Tracking Code

This code is based on the geolocation code from Chapter 4. It is contained in the tracker.js JavaScript file.

/*

* Track and report the current location */

var handlePositionUpdate = function(e) { var latitude = e.coords.latitude; var longitude = e.coords.longitude;

log("Position update:", latitude, longitude); if(navigator.onLine) {

uploadLocations(latitude, longitude);

}

storeLocation(latitude, longitude);

}

var handlePositionError = function(e) { log("Position error");

}

var uploadLocations = function(latitude, longitude) { var request = new XMLHttpRequest();

request.open("POST", "http://geodata.example.net:8000/geoupload", true); request.send(localStorage.locations);

}

var geolocationConfig = {"maximumAge":20000};

navigator.geolocation.watchPosition(handlePositionUpdate,

handlePositionError,

geolocationConfig);

Adding Storage Code

Next, add the code that writes updates to localStorage when the application is in offline mode.

var storeLocation = function(latitude, longitude) { // load stored location list

var locations = JSON.parse(localStorage.locations || "[]"); // add location

310