+ All Categories
Home > Documents > Html 5 Revolution

Html 5 Revolution

Date post: 21-Aug-2015
Category:
Upload: qwert789
View: 2,987 times
Download: 5 times
Share this document with a friend
Popular Tags:
65
Brief History of web standards Why HTML 5 and When? W3C Specification Html Structure Forms Video and Audio HTML 5 and web standards Canvas Data Storage Offline Drag and Drop Geolocation Web Sockets
Transcript
Page 1: Html 5 Revolution

Brief History of web standards

Why HTML 5 and When?

W3C Specification

Html Structure

Forms

Video and Audio

HTML 5 andweb

standardsCanvas

Data Storage

Offline

Drag and Drop

Geolocation

Web Sockets

Page 2: Html 5 Revolution

First Things First Let’s Understand The

History

Page 3: Html 5 Revolution

1999: HTML 4,01 -W3C decide that they would not continue to evolve HTML

2000: XHTML 1- A XML version of HTML requiring XML syntax rules like quoting attributes,

2001: XHTML 1,1-Transitional,and Strict and Frameset become a valid professional-standard

2002: XHTML 2-W3C decide to make more logical ,better designed language and broke backwards compatibility,,,

2002-2003: Opera proof of concept: Web Forms 1.0

2003: XForms – A Model-View-Container approach

2004: WHATWG -Web Hypertext Application Technology Working Group

2007: HTML 5

History of HTML:

Page 4: Html 5 Revolution

HTML 5 Why , When , What?“...extending the language to better support Web applications [...] This puts HTML in direct competition with other technologies[...] , in particular Flash and Silverlight.”

Eventually, 3D canvas

Web Sockets

More Semantic HTML tags

Media Tags Geolocation Canvas Input TypesForm Validation

Cross-Domain Messaging

Local StorageDraggableForm Validation

Changes in the markup• New document type• New elements• Allows more semantic web pages

New APIs are available• 2D drawing• Timed media playback• Offline storage• Etc. (will be discussed later)

Page 5: Html 5 Revolution

HTML5 will reach the Proposed Recommendation Stage sometime in 2022”.

Is HTML 5 ready for production yet? W3C don’t think so!

The problem we’re facing right now is there is already a lot of excitement for HTML 5, but it’s a little too early to deploy it because we’re running into interoperability issues”

The specification is still in draft so it is reasonable to assume that some aspects may possibly change. Browsers therefore can’t be expected to get it right, or implement it in the same way as each other, thus going against the main aim of HTML 5

The Answer:

Page 6: Html 5 Revolution

There won’t be a single point in time at which wecan declare that the language [HTML5] is ready touse. Instead, we can start using parts of thespecification as web browsers support thoseFeatures

So can we use it now or not?

Page 7: Html 5 Revolution

But wait which of browser currently

support the HTML 5?

Page 8: Html 5 Revolution

W3C Specification Where we are? What’s

done?

Page 9: Html 5 Revolution

W3C

HTML

HTM

L5Canvas 2D

ContextM

icrodataH

TML+RD

FaH

TML5 M

arkupH

TML5 D

iff from H

TML4

Polyglot Markup

Text alternatives

CSS

CSS Snapshot 2007CSS N

amespaces

CSS Paged Media

CSS Print ProfileCSS Values and U

nitsCSS Cascading and Inheritance

CSS TextCSS W

riting Modes

CSS Line Grid

CSS RubyCSS G

enerated Content for Paged Media

CSS Backgrounds and BordersCSS Fonts

CSS Basic Box Model

CSS Multi-colum

n LayoutCSS Tem

plate LayoutCSS M

edia Queries

CSS SpeechCSS Color

CSS Basic User Interface

CSS ScopingCSS G

rid PositioningCSS Flexible Box Layout

CSS Image Values

CSS 2D Transform

ationsCSS 3D

Transformations

CSS TransitionsCSS Anim

ations

Web Apps

CORS

Element TraversalFile API

Index DB

Programm

able HTTP Caching and Serving

Progress EventsSelectors API

Selectors API L2Server-Sent Events

Uniform

Messaging Policy

Web D

OM

CoreW

eb SQL D

atabaseW

eb IDL

Web Sockets APIW

eb StorageW

eb Workers

XmlH

ttpRequest

XmlH

ttpRequest L2

DO

M L1

DO

M L2 Core

DO

M L2 View

sD

OM

L2 EventsD

OM

L2 StyleD

OM

L2 Traversal and RangeD

OM

L2 HTM

LD

OM

L3 CoreD

OM

L3 EventsD

OM

L3 Load and SaveD

OM

L3 ValidationD

OM

L3 XPathD

OM

L3 Views and Form

atting

DO

M L3 Abstract Schem

asSVG

Docum

ent StructureBasic Shapes

PathsText

Transforms

Painting, Filling, ColorScriptingStyling

Gradients and Patt

ernsSM

ILFontsFilters

Geolo

catio

nG

eolocation API

ECMA

ECMA Script

262

ECMAScript 262

First Public Working Draft Working Draft

Candidate Recommendatio

nRecommendationLast Call

The Map of HTML 5 Specs:

Page 10: Html 5 Revolution

• Attribute quotes “not really” required

• UPPERCASE and lowercase HTML elements allowed (CaMeLcAse typing)

• No more need to do self-closing tags like <img/> or <BR/>

• Also, no more minimization, So, this is okay <dl compact>

• Basically, everything that was bad from HTML 4 in HTML 5 good again,

Re-Learning Syntax:

Page 11: Html 5 Revolution

STARTING OUT BASIC HTML 5

LAYOUT

Page 12: Html 5 Revolution

XHTML 1,0 Transitional :<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Sample Document</title> <link href="Styles/Site.css" rel="stylesheet" type="text/css" /> <script src="Scripts/jquery.js" type="text/javascript"></script></head>

HTML 5:<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>Sample Document</title> <link href="Styles/Site.css" rel="stylesheet"/> <script src="Scripts/jquery.js"></script>

Page 13: Html 5 Revolution

But wait there is more, if we go to w3c and try to validate this:http://validator.w3.org/#validate_by_input

Then we type the following HTML (below) and hit validate:<!DOCTYPE html><title>Small HTML5</title><p>HELLO WORLD </p>

Syntax:

Page 14: Html 5 Revolution

<body>    <header>        <hgroup>            <h1>Demo page</h1>            <h2>Semantic sample demo page</h2>    </hgroup>    </header>

    <nav>        <ul>            Some nice looking navigation        </ul>    </nav>

    <section>        <article>            <header>                <h1>First Paragraph</h1>            </header>        <section>            Lorem ipsum …        </section>    </article>

    <aside>        Some links and useful side notes    </aside>

    <footer>        Timmy Kokke - Copyright © 2010.    </footer></body>

<HEADER>

<NAV>

<ASIDE>

<FOOTER>

<ARTICLE>

<SECTION>

<Figure>

Img,video,audio

legend

Page 15: Html 5 Revolution

<header> <h1>Title</h1> </header> <section> Content... </section> </article> </section>

<aside> Top links... </aside>

<figure> <img src="..."/> <figcaption>Chart 1.1</figcaption> </figure>

<footer> Copyright © <time datetime="2010-11-08">2010</time>. </footer>

<body> <header> <hgroup> <h1>Page title</h1> <h2>Page subtitle</h2> </hgroup> </header>

<nav> <ul> Navigation... </ul> </nav> <section> <article> <header> <h1>Title</h1> </header> <section> Content... </section> </article> <article

Page 16: Html 5 Revolution

<header> Defines a header for a section or page

<nav> Defines navigation links

<aside> Defines content aside from the page content

<article> Defines an article

<section> Defines a section

<footer> Defines a footer for a section or page

<header>

<nav>

<article>

<footer>

<aside><section>

<!DOCTYPE HTML><html><body><header> <h1>Title</h1></header><nav> <a href=“home.html”>Home</a> <a href=“about.html”>About</a></nav><article> <h1>Article title..</h1> <p>Text…..</p></article><section> <p>Section1</p></section><aside> <p>About us…<p></aside><footer> <p>All rights received</p></footer></body></html>

Page 17: Html 5 Revolution

Article VS Aside VS Section VS Div

• Section- is a thematic grouping of content, typically with a heading –pretty generic, it can contain articles as well and appear as requested.

• Article- is a discrete piece of content that could be syndicated –a blog post, a news item, a comment, a widget.

• Aside- is content that is tangentially related to its parent element. Or ,if a sibling to the main content, it can be used to make sidebars of navigations, recent comments, colophons, author bios etc.

• Div –has no semantic unless group stuff for styling.

Page 18: Html 5 Revolution

current and old browsers “support” these(although some need a little extra help)header, footer, … { display: block; }

Internet Explorer needs extra training wheelsdocument.createElement('header');document.createElement('nav');document.createElement('section');document.createElement('article');document.createElement('aside');document.createElement('footer');http://html5doctor.com/how-to-get-html5-working-in-ie-and-firefox-2

But what about IE 6-8?

http://code.google.com/p/html5shim/

http://www.modernizr.com/

Page 19: Html 5 Revolution

HTML 5 Redefined Element:

<ol>-has a new reversed attribute (not implemented yet), also start attribute is valid

<dl>- Not a Term and Definition anymore it’s a groups of name-value data

<cite>- been used to mark up the name of a speaker of citation ,no it’s specifies a citation only

<address>- been used as generic element for postal addresses, now it’s more global:

is for contact details of the author of the current <article> or document (more then one times)

<em>- marks up emphasis of the kind that subtly changes the meaning of a sentence

<i>- represents a span of text in an alternate voice or mood, or otherwise offset from the normal prose

<strong>- represents strong importance for its contents

<b>- represents a key words or spans of text whose typical typographic presentation is boldened

<hr>- is now media-independent and indicates “aparagraph-level thematic break.”

<small>- not just small text it’s a “small print” licensing requirements.” or copyrights

<p>The <i>Titanic</i> sails at dawn.</p><p>The design needs a bit more <i lang=fr>ooh la la</i>.</p><p>You, sir, deserve a jolly good kick up the <i>gluteusmaximus</i>!</p>

Page 20: Html 5 Revolution

HTML 5 Unsupported Element:

Used for defining an embedded applet. An alternative you could consider using is the new <embed> tag.

Used for defining a base font color, size, or font family for an entire document. You should already be doing this using CSS on the body selector,

Used for making text bigger. An easy alternative to this would be to use some CSS to create a class called .big. Then wrap any text you want to be big in a tag with

Used to center text or elements.

Used to define a directory list

Used to define a frame. Side Note: YES! NO MORE FRAMES! Alternative? Study layout design and hierarchy.

Used to define a frame set.

Used to display text for browsers that didn't support frames. I don't think an alternative is required.<noframes>Used to put a strikethrough text. As an alternative, you can use the <del> tag.<s>Used to put a strikethrough text. As an alternative, you can use the <del> tag.<strike>Used to define teletype text. As an alternative, use CSS to style the particular text with a class.<tt>Used to add an underline to text. As an alternative, use the CSS text-decoration property.<u>Used to define pre-formatted text. Instead, you should use the <pre> tag,<xmp>

Used for defining an acronym. For example, NHL. There's not a clear cut alternative, consider using <section> or <mark>

<acronym>

<applet>

<basefont>

<big>

<center>

<dir>

<frame>

<frameset>

Full List: http://www.html-5.com/changes/deprecated/

Page 21: Html 5 Revolution

Html 5 New API Available

Page 22: Html 5 Revolution

HTML 5 New Selectors API:

var el = document.getElementById('section1');el.focus();var els = document.getElementsByTagName('div');els[0].focus();var els = document.getElementsByClassName('section');els[0].focus();

Finding elements by CSS syntax (Selectors API):var els = document.querySelectorAll("ul li:nth-child(odd)");var tds = document.querySelectorAll("table.test > tr > td");var el = document.querySelector("table.test > tr > td"); // el == tds[0]

Return the first element in the page which matches the specifiedm selector rules(s)

Returns all elements which match thespecified rule or rules

Finding elements by class (DOM API)

Page 23: Html 5 Revolution

Custom data-* attributes:

<div id="out" data-id="good" data-name="joe" data-screen-name="user1"></div>

Define, store, and retrieve custom data on the DOM:

// Add new data attributes via JS.var el = document.querySelector('#out');el.setAttribute('data-foo', 'bar');var html = [];for (var key in el.dataset) { html.push(key, ': ', el.dataset[key], '<br>');}el.innerHTML = html.join('');

Output:id: goodname: joescreenName: user1foo: bar

Page 24: Html 5 Revolution

WAI-ARIA Attributes:

<ul id="tree1" role="tree" tabindex="0" aria-labelledby="label_1"> <li role="treeitem" tabindex="-1" aria-expanded="true">Fruits</li> <li role="group"> <ul> <li role="treeitem" tabindex="-1">Oranges</li> <li role="treeitem" tabindex="-1">Pineapples</li> ... </ul> </li></ul>

Web Accessibility Initiative’s Accessible Rich Internet Applications

• application

• article

• banner

• complementary

• contentinfo

• document

• form

• heading

• main

• navigation

• search

Page 25: Html 5 Revolution

Manipulate Class in native way:

<div id="main" class="shadow rounded"></div>

var el = document.querySelector('#main').classList;el.add('highlight');el.remove('shadow');el.toggle('highlight');

console.log(el.contains('highlight')); // falseconsole.log(el.contains('shadow')); // falseconsole.log(el.classList.toString() == el.className); // true

Output:<div id="main" class="rounded"></div>

Page 26: Html 5 Revolution

THE BEATY OF THE WEBHTML 5 DEMO

Page 27: Html 5 Revolution

Improved Forms Making Common UI Needs

Native

Page 28: Html 5 Revolution

Rich Form Elements – without JavaScript

<input type=”date”><input type=”time”><input type=”month”><input type=”week”><input type=”datetime” … ><input type=”range”><input type=”number”><input type=”file” multiple><input … autofocus><input … autocomplete>

Page 29: Html 5 Revolution

Built-in Validation(with attributes )

<input … required><input type=”tel”><input type=”email”><input type=”url”><input … pattern="[a-z]{3}[0-9]{3}">

Demos:http://people.opera.com/patrickl/experiments/forms/newtypes.htmlhttp://people.opera.com/patrickl/experiments/forms/date-time.htmlhttp://people.opera.com/patrickl/experiments/forms/validation.htmlhttp://people.opera.com/patrickl/experiments/forms/progress.html

Page 30: Html 5 Revolution

HTML 5 New Form Options:

Placeholder-displays init text

Autofocus-focus form on element

Required-prevent form submissions if required fields haven’t been filled out

Autocomplete-automatically filling in forms

Datalist-allows you to crossbreed a regular input element with a select element.

Enter Search Value.. Search<input id="status" name="status" type="text" autofocus>

<form action="/selfdestruct" autocomplete="off">

<input type="text" name="hworld“ list="planets"> <datalist id="planets">

<option value="Mercury"> <option value="Venus">

</datalist>

<input id="pass" name="pass" type="password" required>

Page 31: Html 5 Revolution

THE BEATY OF THE WEBHTML 5 DEMO

Page 32: Html 5 Revolution

Native <video> And Improved <audio>

Page 33: Html 5 Revolution

New HTML5 <video> as native object

<video src="video.mp4" id="videoTag" width="640px" height="360px">

<video src="video.webm" controls autoplay poster="poster.jpg" width="320“ height="240"> <a href="video.webm">Download movie</a>

</video></video>

Industry-standard MPEG-4/H.264 video

Video can be composited with anything else on the page• HTML content, images, SVG graphics• Hardware accelerated, GPU-based decoding

Page 34: Html 5 Revolution

Video as native object-what does it means?

● “ ” plays nice with rest of the page● keyboard accessibility built-in● API for controls: v = document.getElementById('myVideo'); v.play();v.pause(); Demos:http://people.opera.com/patrickl/experiments/webm/basic-controls/http://people.opera.com/patrickl/experiments/webm/fancy-controls/http://people.opera.com/patrickl/experiments/webm/fancy-swap/

Page 35: Html 5 Revolution

A Big Debate about video formats

ubiquitous, patent encumbered, licensing/royalties

“free and open”, no licensing/royalties not many tools

for it, not web optimised

open and royalty-free, web optimized support by software and

hardware vendors

MP4 / H.264 Ogg Theora WebM

Page 36: Html 5 Revolution

Providing HTML 5 Cross Browser <video>

<video controls autoplay poster="…" width="…" height="…"> <source src="movie.webm" type="video/webm" /> <source src="movie.ogv" type="video/ogg" /> <source src="movie.mp4" type="video/mp4" /> <!-- fallback content --> <object width="640" height="360" type="application/x-shockwave-flash" data="__FLASH__.SWF"> <param name="movie" value="__FLASH__.SWF" /> <param name="flashvars“ value="controlbar=over&amp;image=__POSTER__.JPG&amp;file=__VIDEO__.MP4" /> <img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__" title="No video playback capabilities, please download the video below" />

</object> </video>

still include fallback for old browsershttp://camendesign.com/code/video_for_everybody

Page 37: Html 5 Revolution

HTML 5 Nice Audio:

Industry-standard MP3 and AAC audio Fully scriptable via the DOM

<audio id="audioTag" autoplay controls preload=“none”> <source src="witchitalineman.ogg" type="audio/ogg"> <source src="witchitalineman.mp3" type="audio/mpeg"> <!–- Flash Fallback--> <object type="application/x-shockwave-flash" data="player.swf?soundFile=witchitalineman.mp3"> <param name="movie"value="player.swf?soundFile=witchitalineman.mp3"> </object>

</audio>

<div> <button onclick="document.getElementById('player').play()"> Play </button> <button onclick="document.getElementById('player').pause()"> Pause </button> <button onclick="document.getElementById('player').volume+= 0.1"> Volume Up </button> <button onclick="document.getElementById('player').volume-= 0.1"> Volume Down</button>

</div>

Simple JS API:Simple JS API:

Page 38: Html 5 Revolution

HTML 5 Media Basic Controls:

Autoplay- plays the video or audio automatically

Controls - providing controls may be overwritten

Poster - points to an image that the browser will use while the video is downloading

height, width - size in pixels of the video

Loop- loops the media playback

Preload- suggest to buffer the media, before control is activated

<video src="video.mp4" id="videoTag“ poster=“post.jpg” width="640px" height="360px“ autoplay=“false” controls loop preload=“auto” preload=metadata></video>

Page 39: Html 5 Revolution

Video and Audio Fallback:

Good way to include fallback for all browsers

http://mediaelementjs.com

Page 40: Html 5 Revolution

Html5 Canvas The future of graphics on

the Web

Page 41: Html 5 Revolution

What is Canvas?

A block element that allows developers to draw 2d graphics using JavaScript

Methods for drawing include: paths, boxes, circles, text and rasterized images

...also it’s supporting video and audio

<canvas id="myCanvas" width="200" height="200"> Your browser doesn’t support Canvas, sorry.</canvas>

<script type="text/javascript"> var ctx = document.querySelector(‘canvas’).getContext(‘2d’); ctx.fillStyle = "rgb(255,0,0)"; ctx.fillRect(30, 30, 50, 50); ctx.strokeStyle = ‘rgb(0, 0, 0)’; ctx.lineWidth = 5; ctx.strokeRect(9, 19, 52, 52); // draws an outline</script>

Page 42: Html 5 Revolution

What is SVG(Scalable Vector Graphics)?

Create and draw 2D vector graphics using XML• Vector images are composed of shapes instead of pixels• Based on SVG 1.1• Rendered optimally on all sizes of devices

<svg width="400" height="200" xmlns="http://www.w3.org/2000/svg"> <rect fill="red" x="20" y="20" width="100" height="75" /> <rect fill="blue" x="50" y="50" width="100" height="75" /></svg>

For more info visit: http://www.svgbasics.com/

Page 43: Html 5 Revolution

Fallback/Helpful JS Libraries:

Raphael (SVG) – Dmitry Baranovskiyhttp://www.raphaeljs.com/

Processing JS (Canvas) – John Resighttp://www.processingjs.org/

Page 44: Html 5 Revolution

THE BEATY OF THE WEBHTML 5 DEMO

Page 46: Html 5 Revolution

When Canvas or SVG

SVG->High Level

-Import/Export

-Easy UI

-Iterative

-Medium Animation

-Tree of Objects

-Layer based

-Separate files

Canvas->Low Level

-No mouse Interaction

-High Animation

-JS Centric

-More Bookkeeping

-Pixels

-Html Element

VS

Page 47: Html 5 Revolution

Data Storage Expect the Unexpected

Page 48: Html 5 Revolution

Finally Web Storage Here(Cookies suck):

// use localStorage for persistent storage// use sessionStorage for per tab storagetextarea.addEventListener('keyup', function () {  window.localStorage.setItem('value', area.value);  window.localStorage.setItem('timestamp', (new Date()).getTime());}, false);textarea.value = window.localStorage.getItem('value');

<textarea id="ta" placeholder="Type your text here..."></textarea>

Page 49: Html 5 Revolution

THE BEATY OF THE WEBHTML 5 DEMO

Page 50: Html 5 Revolution

Web SQL Database:

if (window.openDatabase) {//always do a HTML 5 feature Check var db = window.openDatabase("DBName", "1.0", "description", 5*1024*1024); // open or create a db db.transaction(function(tx) {  tx.executeSql(‘CREATE TABLE IF NOT EXISTS tweets(id, date, tweet)’, [], function () {

// now go and load the table up with tweets }); }); }

var idbRequest = window.indexedDB.open('Database Name');idbRequest.onsuccess = function(event) { var db = event.result; var transaction = db.transaction([], IDBTransaction.READ_ONLY); var curRequest = transaction.objectStore('ObjectStore Name').openCursor(); curRequest.onsuccess = ...;};

Chrome -Supported in version 3.0 and greater

Firefox -Supported in version 3.0 and greater

IE -Supported in version 9.0 and greater

Opera -Supported in version 10.5 and greater

Safari -Supported in version 4.0 and greater

IndexedDB:

http://hacks.mozilla.org/2010/06/comparing-indexeddb-and-webdatabase/

Page 51: Html 5 Revolution

THE BEATY OF THE WEBHTML 5 DEMO

Page 52: Html 5 Revolution

OfflineHow the WEB can be Offline?

Page 53: Html 5 Revolution

Application Cache:

CACHE MANIFEST

# version 1

CACHE:/html5/src/refresh.png/html5/src/logic.js/html5/src/style.css/html5/src/background.png

<html manifest="cache.manifest">window.applicationCache.addEventListener('checking', updateCacheStatus, false);

cache.manifest:

Page 54: Html 5 Revolution

THE BEATY OF THE WEBHTML 5 DEMO

Page 55: Html 5 Revolution

Drag and DropThe Native API

Page 56: Html 5 Revolution

Native Drag & Drop:

document.addEventListener('dragstart', function(event) { event.dataTransfer.setData('text', 'Customized text'); event.dataTransfer.effectAllowed = 'copy';}, false);

Drag files in from the desktop:document.querySelector('#dropzone').addEventListener('drop', function(e) { var reader = new FileReader(); reader.onload = function(evt) { document.querySelector('img').src = evt.target.result; }; reader.readAsDataURL(evt.dataTransfer.files[0]);}, false);

<div draggable="true">This element be draggable</div>

Page 57: Html 5 Revolution

Desktop Drag-Out

<a href="src/star.mp3" draggable="true" class="dragout" data-downloadurl="MIMETYPE:FILENAME:ABSOLUTE_URI_TO_FILE">download</a>

var files = document.querySelectorAll('.dragout');for (var i = 0, file; file = files[i]; ++i) { file.addEventListener('dragstart', function(e) { e.dataTransfer.setData('DownloadURL', this.dataset.downloadurl); }, false);}

Drag files out onto the desktop:

Page 58: Html 5 Revolution

Geolocation Where is me?

Page 59: Html 5 Revolution

Geolocation:

if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var coords = position.coords; }, errorHandler, {

enableHighAccuracy: true, //use GPS for helptimeout: 2000, //wait before errormaximumAge: 0 //time of use cached position

});}

getCurrentPosition -is a one-shot method for grabbing the user’s current location.

watchPosition -keeps an eye on their position and keeps polling at regular intervals to see if their location has changed.

clearWatch- clears particular watch

Page 60: Html 5 Revolution

Device Orientation:

window.addEventListener('deviceorientation', function(event) {//detect significant change in orientation occurs var a = event.alpha; var b = event.beta; var g = event.gamma;});

Page 61: Html 5 Revolution

Web SocketsTwo-Way Communication

Page 62: Html 5 Revolution

Web Workers (Threads):

onmessage = function (event) { if (event.data == “hello worker!”) { postMessage(“hello there, right back at you”); } else { postMessage(“Can’t you see I’m busy, leave me alone”); }};

if (typeof Worker != “undefined”) {//always perform a feature detection var worker = new Worker('task.js'); worker.postMessage(‘hello worker!’); worker.onmessage = function (event) { alert(‘The worker just sent me this: ‘ + event.data); };}

main.js:

task.js:

A worker is a way of running a discrete block of JavaScript in a background process to the main browser.

Page 63: Html 5 Revolution

What you can do inside a worker?

• postMessage and listen for inbound messages via onmessage

• close, to end the current worker

• Set event listeners

• XMLHttpRequest, for Ajax requests

• Timers, such as setTimeout, setInterval, and their clearing counterparts

• All the core JavaScript functions: eval, isNaN, escape, etc.

• Location object, the href of the worker script

• Web Sockets (which we’ll discuss in the final section of this chapter)

• Web SQL Databases

• Web Workers

• importScripts

Page 64: Html 5 Revolution

Web Sockets:

var socket = new WebSocket("ws://localhost:8000/socket/server/startDaemon.php");socket.onopen = function(event) { socket.send('Hello, WebSocket');};socket.onmessage = function(event) { alert(event.data); }socket.onclose = function(event) { alert('closed'); }

WebSockets is a technique for two-way communication over one (TCP) socket, a type of PUSH technology. Both the server and client can send data at any time, or even at the same time. Only the data itself is sent, without the overhead of HTTP headers, dramatically reducing bandwidth

http://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/

Page 65: Html 5 Revolution

Notification:

if (window.webkitNotifications.checkPermission() == 0) { // you can pass any url as a parameter window.webkitNotifications.createNotification(tweet.picture, tweet.title, tweet.text).show();} else { window.webkitNotifications.requestPermission();}


Recommended