Advanced HTML5
Craig Shoemaker
1. Offline Applications
- Browser Events + Application Cache
- Manifest, Assets, Application Cache, Online Status Awereness
<html manifest="journal-manifest.aspx">
CACHE MANIFEST
# version 1.1
CACHE:
journal.aspx
journal-css.aspx
scripts/jquery-1.5.1.min.js
offline.js
journal-bkg.jpg
NETWORK;
journal/list
FALLBACK:
/home /journal-fallback.aspx
- If one file gives a 404, none will work offline.
- Network are pages you do not want to be cached.
- Fallback if offline different from online.
- The manifest must have mime type: text/cache-manifest with encoding utf-8.
Browser Caching (images, css, javascript)
Application Caching (manifest, html, images, css, scripts)
- Do not mix browser with application caching!
Response Headers
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
- window.applicationCache
- checking - downloading - progress - cached (updated manifest)
- checking - no update (if manifest not updated)
Cache States
0 UNCACHED Cache not initialized
1 IDLE Cache not being updates
2 CHECKING Looking at manifest changes
3 DOWNLOADING Serving files in manifest to browser
4 UPDATEREADY All files in manifest are downloaded
5 OBSOLETE Contents of cache are stale and need to be downloaded again
this.Response.Cache.SetCacheability(HttpCacheability.NoCache);
<%@ Page ContentType="text/cache-manifest" ResponseEncoding="utf-8" ... >
offline.js
$(function() {
window.applicationCache.onupdateready = function(e) {
applicationCache.swapCache();
location.reload();
}
window.applicationCache.onchecking = function(e) {}
window.applicationCache.oncached = function(e) {}
window.applicationCache.onnoupdate = function(e) {}
window.applicationCache.onobsolete = function(e) {}
window.applicationCache.ondownloading = function(e) {}
window.applicationCache.onerror = function(e) {}
window.addEventListener("online", function(e) {}, true);
window.addEventListener("offline", function(e) {}, true);
}
function isOnline()
{
return navigator.onLine;
}
2. Geolocation
IP Address: available everywhere, processed server side, low accuracy, high processing overhead
Coordinate Triangulation
GPS: high accuracy, long operation, not optimal for indoors, hardware required
WiFi: accurate, works indoors, quick & cheap response, ineffective in areas with limited access points
Cell Phone: fairly accurate, works indoors, quick & cheap response, Request access to cell phone or modem, ineffective in areas with few cell towers
User-Defined: high accuracy, flexibility to designate alternative locations, maybe fastest option, can be very inaccurate (esp. if locations change)
- All major browsers from ie8.
Reset location permissions
IE - Options - Privacy - Location - Clear Sites
Chrome - Options - Under the hood - Privacy - Content Settings - Location - Manage Exceptions
Safari/Firefox/Opera - Processes each request individually
var options = {
enableHighAccuracy:true; //default is false
timeout:10000, //in milliseconds, default is no limit
maximumAge:1000 //in milliseconds, default is 0 which is recalculate immediately
};
navigator.geolocation.getCurrentPosition(showPosition, positionError, options);
watchId = navigator.geolocation.watchPosition(showPosition, positionError);
navigator.clearWatch(watchId);
3. Web Storage
- Local + Session (per session, per domain)
- Client-controlled between 2 and 10MB (mostly around 5MB)
- Web storage has simple api with key/value pair (vs IndexedDB)
- All browsers support (only IE supports storage event)
if (window.localStorage)
{
if( window.localStorage.myKey != null) {}
}
window.localStorage.removeItem("myKey");
var session = window.sessionStorage;
var dataString = JSON.stringify(data);
session.setItem("cart", dataString);
var data = JSON.parse(session.getItem("cart"));
window.addEventListener("storage", displayStorageEvent, false);
if (typeof(window.onstorage) == "undefinded") { alert('not for this browser'); }
function displayStorageEvent(e) {
$("#key").html(e.key);
$("#newValue").html(e.newValue);
$("#oldValue").html(e.oldValue);
$("#url").html(e.url);
// e.storageArea <- reference to either Local or Session instance
}
var storage = window.localStorage;
try {
...
storage.length
storage.remainingSpace //only IE
...
} catch (e) {
...
QUOTA_EXCEEDED_ERR
...
}
storage.clear
4. Web Workers
- Background threads in the browser.
- Dedicated to the window.
- Shared to the browser, however not yet implemented in most browsers.
- No access to DOM, Window, Host page (lot of libraries might not work)
- You have access to Navigator(appName, appVersion, platform, userAgent), Timers, XmlHttpRequest
- IE doesn't support it yet. (http://bit.ly/r5BSTI or http://bit.ly/oiOiLT for alternative solutions)
- Arguments between UI and worker are copies.
function getWorker() {
if (_worker == null) {
_worker = new Worker("fib-worker.js");
_worker.onmessage = messageHandler;
_worker.onerror = errorHandler;
}
return _worker;
}
getWorker().postMessage(seriesLength);
getWorker().terminate(); //will terminate immediately
this.close(); //from within the worker will terminate on completion
function messageHandler(e) {
var results = e.data;
}
function generate(n) {
...
postMessage(results);
}
//basic ajax call
var xmlhttp;
if (XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
postMessage(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "ajax-content.htm", true);
xmlhttp.send();
5. Web Sockets
- Bidirectional, full duplex client/server communication.
- Real time data before web sockets: ajax + comet
Polling, long polling & streaming.
Http Header: 100's of bytes vs Socket Header: 2 bytes
Some browsers turn it off because of security.
firefox - about:config - network.websocket
opera - config#UserPrefs|EnableWebSockets
interface ISocketServer
{
void Initialize(string serverPath, string originServerAndPort);
void Start();
void Send();
string Input { set; }
}
var server = new WebSocket("ws://localhost:8181/server");
server.addEventListener("message", messageHandler, false);
server.addEventListener("open", openHandler, false);
server.addEventListener("close", closeHandler, false);
function messageHandler(e) { logMsg("Server says: " + e.data); }
Stock Ticker example
- jStockTicker.js to display the scrollbar.
- NBuilder to generate dummy data.
6. Microdata
- Standard HTML Markup + Vocabulary namespace
<div id="container" itemscope itemtype="http://data-vocabulary.org/Person">
<h2 itemprop="name">Ken Van Gilbergen</h2>
<span itemprop="address" itemscope itemtype="http://data-vocabulary.org/Address">
<span itemprop="region">CA</span>
</span>
</div>
Microdata Property Value Origins
<img src="src" itemprop="photo" /> //will take source
<a href="link" itemprop="affiliation">some text</a> //will take href
<time itemprop="startDate" datetime="somedate">Feb 29, 9:00PM</time> //will take datetime attribute
itemid: uniquely identifies at scope-level
itemref: pointer to microdata values not included in itemscope
itemref will contain a list of ids of elements separated by spaces.
<a href="mylocation" itemprop="url"><span itemprop="affiliation">MyCompany</span></a>
<meta itemprop="currency" content="USD">