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

CHAPTER 12 CREATING OFFLINE WEB APPLICATIONS

locations.push({"latitude" : latitude, "longitude" : longitude}); // save new location list

localStorage.locations = JSON.stringify(locations);

}

This application stores coordinates using HTML5 local storage as described in Chapter 9. Local storage is a natural fit for offline-capable applications, because it provides a way to persist data locally in the browser. The data will be available in future sessions. When network connectivity is restored, the application can synchronize with a remote server.

Using storage here has the added benefit of allowing recovery from failed upload requests. If the application experiences a network error for any reason, or if the application is closed (by user action, browser or operating system crash, or page navigation) the data is stored for future transmission.

Adding Offline Event Handling

Every time the location update handler runs, it checks the connectivity status. If the application is online, it will store and upload the coordinates. If the application is offline, it will merely store the coordinates. When the application comes back online, it can update the UI to show the online status and upload any data is stored while online.

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

}, true);

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

}, true);

The connectivity status may change while the application is not actively running. For instance, the user may have closed the browser, refreshed, or navigated to a different site. To handle these cases, our offline application checks to see if it has come back online on each page load. If it has, it will attempt to synchronize with the remote server.

// Synchronize with the server if the browser is now online if(navigator.onLine) {

uploadLocations();

}

Summary

In this chapter, you have seen how HTML5 Offline Web Applications can be used to create compelling applications that can be used even when there is no Internet connection. You can ensure that all your files are cached by specifying the files that are part of the web application in the cache manifest file and then referencing the files from the main HTML page of the application. Then, by adding event listeners for online and offline status changes, you can make your site behave differently based on whether an Internet connection is available or not.

In the final chapter, we will discuss the future of HTML5 programming.

311