Peter Lubbers Kaazing#dcodeHTML5WebSockets,Web Workers,andGeolocationUnleashed! 
About Peter LubbersDirector of Documentation and Training, Kaazing (The HTML5 WebSocket Company)
Co-Founder San Francisco HTML5 User Grouphttp://www.sfhtml5.org/
Co-author Pro HTML5 Programming
Ultra Distance Runner
Twitter: @peterlubbersCopyright © 2010 - Kaazing Corporation. All rights reserved.
AgendaAbout HTML5
HTML5 Web Workers
HTML5 Geolocation
HTML5 Web Sockets
Q&A And…the first ones to answer the quiz questions win a free book!Copyright © 2010 - Kaazing Corporation. All rights reserved.
AboutHTML5© 2009 – Kaazing Corporation
HTML5 Paves the Cow PathsDegrade gracefully (Evolution not revolution)
Don't reinvent the wheel (or at least make a better one!)Copyright © 2010 - Kaazing Corporation. All rights reserved.
HTML5: Simple is BetterSimplify wherever possible
Examples:
Native browser ability instead of complex JavaScript code
New doctype
Character set
HTML5 APIs
As they say in Holland: “So simple, a child can do the laundry!”Copyright © 2010 - Kaazing Corporation. All rights reserved.
HTML5 : A Plugin-Free ParadigmHTML5 provides native support for many features that were only possible with plugins or complex hacks
Problems with plugins:
May not be installed
Can be disabled
Are a separate attack vector
Are difficult to integrate with the rest of an HTML document (plugin boundaries, clipping, and transparency issues)“Whenever a Mac crashes more often than not it’s because of Flash.”--Steve JobsCopyright © 2010 - Kaazing Corporation. All rights reserved.
Just Kidding!Copyright © 2010 - Kaazing Corporation. All rights reserved.
Is This HTML5?Many pieces of the HTML5 effort were originally part of the HTML5 specification
Moved to a separate standards document to keep the specification focused
Industry still refers to the original set of features, including Web Sockets, as "HTML5“
See: http://www.whatwg.org/specs/web-apps/current-work/multipage/introduction.html#is-this-html5?Copyright © 2010 - Kaazing Corporation. All rights reserved.
HTML5 Web WorkersCopyright © 2010, Kaazing Corporation,. All rights reserved.
HTML5 Web WorkersWithout Web Workers:
Long-running JavaScript tasks can block other JavaScript on the page
JavaScript can cause some browser UIs to hang
With Web Workers:
Background processing capabilities to web applications can be added
Parallel operations can run concurrentlyCopyright © 2010 - Kaazing Corporation. All rights reserved.
HTML5 Web WorkersWeb Workers are used for
Background number-crunchers
Background notification from server to a local database
Background price updates from server
Search queries
Graceful degradation? Easy!Copyright © 2010, Kaazing Corporation,. All rights reserved.
DemoCopyright © 2010, Kaazing Corporation,. All rights reserved.
Using the Web Workers APICopyright © 2010, Kaazing Corporation,. All rights reserved.
HTML5 Web WorkersCannot access the web page’s window object (window.document)
No direct access to the web page and the DOM API
Can use the full JavaScript timing API, typically found on the global window
Although HTML5 Web Workers cannot block the browser UI, they can still consume CPU cycles and make the system less responsiveCopyright © 2010, Kaazing Corporation,. All rights reserved.
HTML5 Web Workers APICreate an HTML5 Web Worker object and pass in a JavaScript file to be executed
Use Cross Document Messaging API (PostMessage)
On the web page:
Set up an (asynchronous) event listener to listen to incoming messages and errors from the worker
call postMessage to pass data to a worker
On the web page:
Set up an (asynchronous) event listener to listen to incoming messages and errors from the page
call postMessage to pass data to the pageCopyright © 2010, Kaazing Corporation,. All rights reserved.
JavaScript//Check if Web Workers are supportedif (typeof(Worker) !== "undefined") { document.getElementById("support").innerHTML = “Your browser supports HTML5 Web Workers";}//Create a new worker//The URL for the JavaScript file can be a relative or //absolute URL with the same origin //(the same scheme, host, and port) as the main pageworker = new Worker("echoWorker.js");//to load additional JavaScriptimportScripts("helper.js, "anotherHelper.js");Copyright © 2010, Kaazing Corporation,. All rights reserved.
JavaScript//Main Pageworker.postMessage("Here's a message for you");//Add event listenerworker.addEventListener("message", messageHandler, true);//Process incoming messagesfunction messageHandler(e) { // process message from worker}//Handle errorsworker.addEventListener("error", errorHandler, true);//Stop workerworker.terminate();Copyright © 2010, Kaazing Corporation,. All rights reserved.
JavaScript//Workerfunction messageHandler(e) { postMessage("worker says: " + e.data + " too");}addEventListener("message", messageHandler, true);//Using a Web Worker within a Web Worker var subWorker = new Worker("subWorker.js");Copyright © 2010, Kaazing Corporation,. All rights reserved.
Browser SupportChrome 4.0+
Firefox 3.5+
Safari 4.0+
Opera 10.6+* May need to be served up from a server (origin security)Copyright © 2010, Kaazing Corporation,. All rights reserved.
HTML5 GeolocationCopyright © 2010, Kaazing Corporation,. All rights reserved.
Using GeolocationAllows users to share their location for location-aware services
Show user's position on map
Tag content (photos/sound/video)
Turn-by-turn navigation
Alert users of nearby points of interest
Social networkingCopyright © 2010, Kaazing Corporation,. All rights reserved.
DemoCopyright © 2010, Kaazing Corporation,. All rights reserved.
Geolocation ArchitectureCopyright © 2010, Kaazing Corporation,. All rights reserved.
Location DataLocation information consists of a pair of latitude and longitude coordinates and accuracy information
Latitude is the numerical value indicating distance north or south of the equator
Longitude is the numerical value indicating distance east or west of Greenwich, England
For Example, Lake Tahoe:Latitude: 39.17222, Longitude: -120.13778Copyright © 2010, Kaazing Corporation,. All rights reserved.
Location MetadataDepending on the device, additional meta data can be provided:

HTML5 Web Workers-unleashed

Editor's Notes

  • #13 Google Chrome – every tab is its own program (not one tab within a program). So if one tab goes down, the whole app doesn't crash.
  • #16 150 ms (TCP round trip to set up the connection plus a packet for the message)50 ms (just the packet for the message)
  • #26 The following steps are shown in the diagram: A user navigates to a location-aware application in the browser.The application web page loads and requests coordinates from the browser by making a Geolocation function call. The browser intercepts this and requests user permission. Let's assume that the permission is granted.The browser retrieves coordinate information from the device it is running on. For example, the IP address, Wi-Fi, or GPS coordinates. This is an internal function of the browser.The browser sends these coordinates to a trusted external location service, which returns a detailed location that can now be sent back to the host of the HTML5 Geolocation application.
  • #39 The successCallback function parameter tells the browser which function you want called when the location data is made available. This is important because operations such as fetching location data may take a long time to complete. No user wants the browser to be locked up while the location is retrieved, and no developer wants his program to pause indefinitely—especially because fetching the location data will often be waiting on a user to grant permission. The successCallback is where you will receive the actual location information and act on it.However, as in most programming scenarios, it is good to plan for failure cases. It is quite possible that the request for location information may not complete for reasons beyond your control, and for those cases you will want to provide an errorCallback function that can present the user with an explanation, or perhaps make an attempt to try again. While optional, it is recommended that you provide one.Finally, an options object can be provided to the HTML5 Geolocation service to fine-tune the way it gathers data. This is an optional parameter that we will examine later.
  • #41 The timeout value deals with the duration needed to calculate the location value, while maximumAge refers to the frequency of the location calculation. If any single calculation takes longer than the timeout value, an error is triggered. However, if the browser does not have an up-to-date location value that is younger than maximumAge, it must refetch another value. Special values apply here: setting the maximumAge to “0” requires the value to always be re-fetched, while setting it to Infinity means it should never be refetched.
  • #44 This sample works by using the watchPosition() capability we discussed in the last section. Every time a new position is sent to us, we will compare it to the last known position and calculate the distance traveled. This is accomplished using a well-known calculation known as the Haversine formula, which allows us to calculate distance between two longitude and latitude positions on a sphere.
  • #57 High-message volume, small message size scenario where long-polling is potentially worse than polling.
  • #59 WebSocket is text-only
  • #63 HTTP used for handshake onlyOperates over a single socketTraverses firewalls and routers seamlesslyAllows authorized cross-site communicationCookie-based authenticationExisting HTTP load balancersNavigates proxies using HTTP CONNECT, same technique as https, but without the encryption
  • #64 Text type requires high-order bit setBinary type requires high-order bit _not_ setThere is no defined maximum size. However, the protocol allows either side (browser or server) to terminate the connection if it cannot receive a large frame. So far, the definition of too large is left up to the implementation.If the user agent is faced with content that is too large to behandled appropriately, then it must fail the Web Socket connection.There is probably a practical maximum, but we have not discovered it as far as I know.You can't have four gigabytes of data in JavaScript, so the practical max is <4GB for the JavaScript implementation.
  • #69 150 ms (TCP round trip to set up the connection plus a packet for the message)50 ms (just the packet for the message)
  • #70 150 ms (TCP round trip to set up the connection plus a packet for the message)50 ms (just the packet for the message)
  • #74 Text type requires high-order bit setBinary type requires high-order bit _not_ setThere is no defined maximum size. However, the protocol allows either side (browser or server) to terminate the connection if it cannot receive a large frame. So far, the definition of too large is left up to the implementation.If the user agent is faced with content that is too large to behandled appropriately, then it must fail the Web Socket connection.There is probably a practical maximum, but we have not discovered it as far as I know.You can't have four gigabytes of data in JavaScript, so the practical max is <4GB for the JavaScript implementation.