25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

}<br />

// test to make sure that Web Sockets are supported<br />

if (window.WebSocket) {<br />

}<br />

CHAPTER 9 ■ USING THE <strong>HTML</strong>5 WEB STORAGE API<br />

// the location where our broadcast WebSocket server is located<br />

url = "ws://websockets.org:7999/broadcast";<br />

socket = new WebSocket(url);<br />

socket.onopen = function() {<br />

document.getElementById("leaderboardStatus").inner<strong>HTML</strong> = "Leaderboard:<br />

Connected!";<br />

}<br />

socket.onmessage = function(e) {<br />

dataReturned(e.data);<br />

}<br />

This is a longer function than the others, and there is a lot going on. Let’s take it step by step. First,<br />

as shown in Listing 9-9, we do a basic error check to make sure that the browser viewing the page<br />

supports sessionStorage by checking for its presence on the window object. If sessionStorage is not<br />

accessible, we simply update the leaderboardStatus area to indicate as much, and the return out of the<br />

loading routine. We won’t be attempting to work around lack of browser storage in this example.<br />

Listing 9-9. Checking for Browser Support<br />

// make sure the browser supports sessionStorage<br />

if (typeof(window.sessionStorage) === "undefined") {<br />

document.getElementById("leaderboardStatus").inner<strong>HTML</strong> = "Your browser does<br />

not support <strong>HTML</strong>5 Web Storage";<br />

return;<br />

}<br />

■ Note It is possible to rework this demonstration to simply forgo any persistence of data between page<br />

navigations and start each page load with a clean leader board if storage is not supported. However, our goal here<br />

is to show how storage optimizes the experience for both the user and the network.<br />

The next thing we do on page load is to use the storage to retrieve any racer distance results that<br />

have already been served to this or other pages of our website. Recall that we are running an identical<br />

block of script code on every one of our site pages, so that the leader board follows the users as they<br />

browses around various locations. As such, the leader board may already have stored values into storage<br />

from other pages that will be retrieved and displayed here directly on load as shown in Listing 9-10. The<br />

previously saved values will follow the user during navigation, as long as the user does not close the<br />

window, tab, or browser, thus clearing out the session storage.<br />

229

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!