Loading blog entries.. loading

Blogs which referenced tag: [HTML5]


Honored to Win CodeProject HTML5 competition

Written by Wayne Ye  Monday, November 14, 2011

Three months ago, my article <HTML5 WebSocket In Essence> was honored to be named first prize in CodeProject HTML5 & CSS3 competion, the award was an Ipad2. To be very honest I was expecting to win a T-Shirt or a CP Mug, if I could get either on I would be really excited, so when I received the email congratulating me I was the winner, you can image how excited and happy I was at that timeSmile.

However, the editor from CodeProject told me they were unable to ship the Ipad2 to China, they could give me equivalent money - $499.99, however after a very short consideration I decided to take the Ipad, absolutely!

So eventually, today, thanks to my co-workers in Cupertino, I got it, below are photos taken from my Sentation:

First look

First look

The front

The front

The back

The back

The memorable words

The memorable words

There is another "award" in fact, now if I google with keywords: “html5 websocket”, my article appears second resultSmile.


View Post»


Make your HTML5 Video support all browsers

Written by Wayne Ye  Monday, November 7, 2011


HTML5 video tag gave us the following advantages:

  1. No plugin required, directly play.
  2. Visible & controllable for Browser and search engine, not a "black box" such as Flash or SilverLight.
  3. Cross-platform, in theory all PC/mobile browsers as well as Ipad/Windows 8/Android tablet PC. 
  4. Downward compatibility. Which is very important, but W3C had made it simple and works, we can smoothly fall back to flash if the user agent does not recognize "<video>" tag.

So it is simple and pretty cool! However, there is still issues within a not short period: the browser support - each concrete browser and the company (ies) behind it supports different formant of videos, to be more specific, refer the table below stole from about.com:

 AndroidChromeFirefoxInternet ExploreriOSOperaSafari
Codec WinMacWinMacWin WinMacWinMac
MP4 or H.264 3.0 9 7 X X 9 3 X X 5 5
ogg/Theora 2.3 9 7 3.6 3.6 X X 10.63 10.63 X X
WebM 2.3 9 7 3.6 3.6 9 (withcomponents) X 10.63 10.63 X X

So to support all browsers: IE 6.0+, Firefox, Chrome, Safari, Opera, etc, what should we do?

Cross All Browser Implementation

By searching on the google and half a day investigation, I found the solution, sample code pasted below:

 <video controls="controls" preload="auto" poster="napshot.png">
    <source src="My Video.mp4" type="video/mp4" />
    <source src="My Video.webm" type="video/webm" />
    <source src="My Video.ogv" type="video/ogg" />

The code above results in IE 9.0+/Safari will load mp4, Chrome/Firefox and Opera will load webm, and IE 6.0 ~ 8.0 will load flash.

Note: as browsers may change its attitude on the video format support, so my code & comments might not right in the future.  

Few tips

View Post»


HTML5 WebMessaging In Essence

Written by Wayne Ye  Tuesday, August 30, 2011

Download HTML5_Cross-Domain_WebMessaging_Demo.zip - 2.97 KB

As a web developer, sometimes we are easy to encounter one problem: Cross-Domain communication, conforming Same-Origin-Policy, JavaScript code cannot access code stay in different domain(or sub-domain) or protocol (HTTP/HTTPs) or port, so there was no direct (or I can say: simple) way to achieve Cross-Domain Communication. However, those kinds of requirements does happen: page A and page B are in different domain,  B is "embedded" in A, i.e., there is an "iframe" in page A whose "src" is page B's URL, now page A wants to control page B and vise-versa. 

By limiting the solution to be done by 100% client JavaScript, beforehand HTML5, there are a number of tricky "hacks", such as:

  1. URL long polling: container page A changes the iframe page B's URL hash, and B periodically checks the hash, once the hash changed, it takes action according to the contracted hash value. [BTW, the pattern can be revised to be non-polling by HTML5 onchashchange event]
  2. CrossFrame, a Safe Communication Mechanism Across Documents and Across Domains.
  3. Window Size Monitoring: update the iframe's window size once, and the containning window subscribes its "onresize" event then takes corresponding action(s). Google Mapplets adopted this pattern.

Well, personally I really don't like all of them... either inelegant, or violates the original functionalities of DOM elements, or too complecated. I believe many people don't like them too even the pattern inventors I bet... That why WHATWG created Cross-Domain communication in HTML5: Web Messaging.

As an HTML5 crazy advocator I like it very much, complete client communication, no server impact, efficient, secure (at least in theory).

How to

"Child" can be an iframe or an popup window by invocking window.open, "parent page" A contains source code is like below:

 <iframe id="ifr" src="http://domainB.com/B.htm" onload="sendCommand();">
  No frame!

<script type="text/javascript">  
  function sendCommand() {
    var ifr = document.getElementById("ifr");
    ifr.contentWindow.postMessage("Hello", "http://domainB.com");

Notice, make sure post message only when the iframe is loaded, otherwise the contentWindow will be still in same domain with the container page.

Child page B contains code like below:

 <input type="button" value="Cross domain call" onclick="sendMsg();" />

window.addEventListener("message", receiveMessage, false);

function receiveMessage(evt) {
    console.log("Page B received message from origin: %s.", evt.origin);
    console.log("Event data: %s", evt.data);
    //evt.source will be a window who sent the message, it can be used to post message to it
    // Take action(s)

The demo code above is one direction: parent sends message to child (iframe), actually bi-directional message trasfer can also be done, similar with "Parent control child", child page posts message to container window, only different is call "parent.postMessage".

 function receiveMessage(evt) {
    evt.source.postmessage("Hello caller");
    // or parent.postmessage("Hello parent");

Web Messaging Essential

In a nutshell, HTML5 Web Messaging is a suite of JavaScript API exposed by web browser, to communicate between different browsing context, when JavaScript code in one browser tab/window trys to deliver a message to another tab/window, web browser locates the target tab/window under the specified domain, and file a MessageEvent (which inherits from DOMEvent) to the target tab/window, so if the target tab/window already subscribed the message event, it will gets notified, eventually the message got delivered through MessageEvent.data.

Live Demo

I've done a demo in my dev machine, I override my local hosts file to let  Container.com, DomainA.com, DomainB.com and DomainC.com all point to Container.com DomainA.com DomainB.com DomainC.com

I prepared a Container page which contains code below:

 <h3>HTML5 Cross-Domain post message demo</h3>
<p id="infoBar"></p>
<div id="wrapperA">
    <input type="text" id="txtA" /><br />
    <input type="button" value="Post Message" onclick="postMsgToIfr('A');" />
    <br />
    <iframe id="ifrA" src="http://DomainA.com/A.htm"></iframe>
<div id="wrapperB">
    <input type="text" id="txtB" /><br />
    <input type="button" value="Post Message" onclick="postMsgToIfr('B');" />
    <br />
    <iframe id="ifrB" src="http://DomainB.com/B.htm"></iframe>
<div id="wrapperC">
    <input type="text" id="txtC" /><br />
    <input type="button" value="Post Message" onclick="postMsgToIfr('C');" />
    <br />
    <iframe id="ifrC" src="http://DomainC.com/C.htm"></iframe>
<div style="clear: both">
<script type="text/javascript">
    window.addEventListener("message", receiveMessage, false);

    var infoBar = document.getElementById("infoBar");
    function receiveMessage(evt) {
        infoBar.innerHTML += evt.origin + ": " + evt.data + "<br />";

    function postMsgToIfr(domain) {
        switch (domain) {
            case "A":
                var ifr = document.getElementById("ifrA");
                ifr.contentWindow.postMessage(document.getElementById("txtA").value, "http://DomainA.com");
            case "B":
                var ifr = document.getElementById("ifrB");
                ifr.contentWindow.postMessage(document.getElementById("txtB").value, "http://DomainB.com");
            case "C":
                var ifr = document.getElementById("ifrC");
                ifr.contentWindow.postMessage(document.getElementById("txtC").value, "http://DomainC.com");
                throw new error("No such domain!");

And three pages: A.htm located in DomainA.com, B.htm located in DomainB.com, C.htm located in DomainC.com, phisically they all located under C:\inetpub\wwwrooot, while in the browser I manually type DomainA/B/C.com to make the cheatSmile, the code in the A/B/C page are similar, showing below:

<input type="button" value="Cross domain call" onclick="doClick();" />
<div id="d">
    window.addEventListener("message", receiveMessage, false);

    function doClick() {
        parent.postMessage("Message sent from " + location.host, "http://container.com");

    var d = document.getElementById("d");
    function receiveMessage(evt) {
        d.innerHTML += "Received message \"<span style=\"color:red\">" + evt.data + "</span>\" from domain: " + evt.origin + "<br />";

I recorded a gif image below to demonstrate the Cross-Domain messaging:

HTML5 Cross-Domain Messaging Demo

See the message passed through different domain in bi-direction? Isn't it cool?


To support independent communication under different browsing context, HTML5 introduced Message Channel to post message independently, its official definition is showing below:

Communication channels in this mechanisms are implemented as two-ways pipes, with a port at each end. Messages sent in one port are delivered at the other port, and vice-versa. Messages are asynchronous, and delivered as DOM events. 

I spent about half a day in investigating the Message Channel and finally got it worked, my code is showing below:

Container page source code

 <iframe id="ifr" src="http://wayneye.me/WebProjects/HRMS/Opener.html" onload="initMessaging()"></iframe>
<input type="button" value="Post Message" onclick="postMsg();" />
<div id="d"></div>
var d = document.getElementById("d");
var channel = new MessageChannel();
channel.port1.onmessage = function (evt) {
    d.innerHTML += evt.origin + ": " + evt.data + "<br />";

function initMessaging() {
    var child = document.getElementById("ifr");
    child.contentWindow.postMessage('hello', 'http://wayneye.me', [channel.port2]);

function postMsg() {
    channel.port1.postMessage('Message sent from ' + location.host);

iframe page source code

 <div id="info"></div>
<input type="button" value="Post Message" onclick="postMsg();" />
var info = document.getElementById("info");
var port = null;
window.addEventListener("message", function (e) {
    if(e.ports && e.ports.length > 0) {
        port = e.ports[0];
        port.addEventListener("message", function (evt) {
            info.innerHTML += "Received message \"" + evt.data + "\" from domain: " + evt.origin + "<br />";
        }, false);
}, false);

function postMsg() {
    if(port) {
        port.postMessage("Data sent from " + location.host);

The entire process can be described as:

  1. Container page (A) embedded an iframe whose src is pointing to a page (B) in different domain.
  2. Once the iframe loaded, the container posts a message to page B with a MessagePortArray.  
  3. Page B received the message as well as the array containing a list of MessagePort objects.
  4. Page B registers onmessage event on port instance.
  5. Page B invokes port.postmessage to send a message to page A through this MessageChannel. 
At this timestamp, I seems only Opera correctly supports MessageChannel, Google Chrome and IE10 Platform Preview 2 failed to deliver the ports array, Safari cannot gets the onmessage event fired. Firefox 7.0 beta event doesn't support MessageChannel object.
Note: Ports can also enable communication between HTML5 Web Workers.

One more thing (plagiarize Steve JobsSmile), to use Message Channel one noticable point is, web developer should explicitly close the channel once there is no need, otherwise there will be a strong reference between two pages, as W3 official page emphasized below:

Authors are strongly encouraged to explicitly close MessagePort objects to disentangle them, so that their resources can be recollected. Creating many MessagePort objects and discarding them without closing them can lead to high memory usage.

Further reading

HTML5 Web Messaging

window.postMessage - MDN Docs

HTML5 Demo: postMessage (cross domain)

HTML5′s window.postMessage AP

Internet Explorer 10 Platform Preview: HTML5



Also posted on CodeProject: http://www.codeproject.com/KB/HTML/HTML5-WebMessaging.aspx

View Post»


nodejs+express+jade+socket.io on Ubuntu 11.04

Written by Wayne Ye  Monday, August 29, 2011


socket.io is a brilliant project which perfectly supports HTML5 WebSocket, in additional, it can fall back to flash or long polling when the client web browser does not support WebSocket, I explored it today on Ubuntu, I summarized the process in this post.


Install nodejs

I used nodejs v0.4.11, the latest stable version, by mannually compile/make/install.

sudo curl http://nodejs.org/dist/node-v0.4.11.tar.gz -o ~/Desktop/WayneDevLab/node.tar

sudo tar -xf node.tar cd node-v0.4.11



sudo make install

In the "./configure" step above if it prompted "libssl-dev" not found, please install libssl-dev (sudo apt-get install libssl-dev) which is required by node for hosting HTTPs server.

Install npm

curl http://npmjs.org/install.sh | sh

Install express

express is an insanely fast and high performance server-side JavaScript web development framework built on node, hosting a real web server based on node will be much harder without it:)

$ npm install -g express
$ express /tmp/foo && cd /tmp/foo
$ npm install -d 

Install socket.io

npm install socket.io

Setting up the Web server!!

I've modified my app.js as below:

 var express = require('express');

var app = module.exports = express.createServer(),
    io = require('socket.io').listen(app);

// Configuration
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('view options', {layout: false});
  app.use(express.static(__dirname + '/public'));

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

app.configure('production', function(){

// Routes

app.get('/', function(req, res){
  res.render('index', {
      title: 'Wayne Express Hello World',
      youAreUsingJade: true,
      domain: ''

console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {

And below is my index.jade:

!!! 5
    title= title
    script(src='http://'+ domain + ':3000/socket.io/socket.io.js')
      var socket;
      socket =  io.connect('');

      socket.on('news', function (data) {
       socket.emit('my other event', { my: 'data' });
    h1 Wayne WebSocket Demo using Socket.io
      - if (youAreUsingJade)
        p You are amazing
      - else
        p Get on it!

    p Powered By a(href='http://socket.io') Socket.io

    footer Copyright©2011 http://wayneye.com

Testing everything up

Start the server by:

$ node app.js

It works:)

I tested the combination above by using google Chromoum Dev 12 and Dev 15, they seperately adhere WebSocket protocol draft-hixie-thewebsocketprotocol-76 and draft-ietf-hybi-thewebsocketprotocol-10, the connection details for hybi10 is showing below:


socket.io will print out useful information on console when running:

socket.io console


Wish that helps:)

View Post»


HTML5 WebSocket in Essence技术分享

Written by Wayne Ye  Saturday, August 20, 2011

今天下午,我非常荣幸受邀参加HTML5兴趣小组每月一次的沙龙活动,我给大家分享了HTML5 WebSocket的特性,协议本质,以及我的Team Poker demo。







HTML5 WebSocket in Essence on Prezi




View Post»


HTML5 Web Socket in Essence

Written by Wayne Ye  Friday, June 10, 2011

HTML5 WebSocket defines a bi-directional, full-duplex communication channel operates through a single TCP connection, this article discusses its fantastic performance, the WebSocket protocol principle and its handshake mechanism, and develop a WebSocket application in action (Team Poker).

Embeded youku video link because Youtube is outside of the largest "intranet" in the entire universe!!

Table of Content

  1. Introduction
  2. Background
  3. WebSocket In Essence
  4. Experimental Demos
  5. Browser Support
  6. WebSocket JavaScript API
  7. Develop WebSocket In Action - Team Poker
  8. Open Issues
  9. Conclusion
  10. References & Resources 


HTML5 WebSocket defines a bi-directional, full-duplex communication channel that operates through a single TCP socket over the Web, it provides efficient, low-latency and low cost connection between web client and server, based on WebSocket, developers can build scalablereal-time web applications in the future. Section below is the official definition of WebSocket copied from IETF WebSocket protocol page: 

The WebSocket protocol enables two-way communication between a user agent running untrusted code running in a controlled environment to a remote host that has opted-in to communications from that code.  The security model used for this is the Origin-based security model commonly used by Web browsers.  The protocol consists of an initial handshake followed by basic message framing, layered over TCP.  The goal of this technology is to provide a mechanism for browser-based applications that need two-way communication with servers that does not rely on opening multiple HTTP connections (e.g. using XMLHttpRequest or <iframe>s and long polling).

This article is trying to go through WebSocket basic concept, the problems it is going to solve, explain it in essence, watch some experimental Demos, develop a simple WebSocket application in action (Team Poker), and describe current open issues of WebSocket. I sincerely hope it will be systematicallyeasy to understandfrom surface to deep so that eventually readers would not only learn what WebSocket is from high level but also understand it in depth! Any thoughts, suggestions or criticism you may have after reading this article will help me to improve in the future, i would appreciate it if you could leave a comment.


In traditional web applications, in order to achieve some real-time interaction with server, developers had to employ several tricky ways such as Ajax pollingComet (A.K.A Ajax push, Full Duplex Ajax, HTTP Streaming, etc.), those technologies either periodically fire HTTP requests to server or hold the HTTP connection with server for a long time, which "contain lots of additional, unnecessary header data and introduce latency" and resulted in "an outrageously high price tag". websocket.org explained the problems exhaustively, compared the performance of Ajax polling and WebSocket in detail, built up two simple web pages, one periodically communicated with server using traditional HTTP and the other used HTML5 WebSocket, in the testing each HTTP request/response header is approximate 871 byte, while data length of WebSocket connection is much shorter: 2 bytes after connection established, as the transfer count getting larger, the result will be:

Traditional HTTP Request 

  • Use case A: 1,000 clients polling every second: Network throughput is (871 x 1,000) = 871,000 bytes = 6,968,000 bits per second (6.6 Mbps)

  • Use case B: 10,000 clients polling every second: Network throughput is (871 x 10,000) = 8,710,000 bytes = 69,680,000 bits per second (66 Mbps)

  • Use case C: 100,000 clients polling every 1 second: Network throughput is (871 x 100,000) = 87,100,000 bytes = 696,800,000 bits per second (665 Mbps)

HTML5 WebSocket

  • Use case A: 1,000 clients receive 1 message per second: Network throughput is (2 x 1,000) = 2,000 bytes = 16,000 bits per second (0.015 Mbps)

  • Use case B: 10,000 clients receive 1 message per second: Network throughput is (2 x 10,000) = 20,000 bytes = 160,000 bits per second (0.153 Kbps)

  • Use case C: 100,000 clients receive 1 message per second: Network throughput is (2 x 100,000) = 200,000 bytes = 1,600,000 bits per second (1.526 Kbps)

Finally a more readable diagram:

Polling VS WebSocket

 "HTML5 Web Sockets can provide a 500:1 or — depending on the size of the HTTP headers — even a 1000:1 reduction in unnecessary HTTP header traffic and 3:1 reduction in latency".  --WebSocket.org

WebSocket In Essence

The motivation of creating WebSocket is to replace polling and long polling(Comet), and endow HTML5 web application the ability of real-time communication. Browser based web application can fire WebSocket connection request through JavaScript API, and then transfer data with server over only one TCP connection.

View Post»


HTML5 Web Storage in Essence

Written by Wayne Ye  Saturday, February 26, 2011


Web Storage (also named Dom storage) is a brand new mechanism of storing temporary/permanent data introduced in HTML5 to replace cookie, it contains two new DOM objects: sessionStoragy and localStorage), in Web Storage Spec, Ian Hickson documented that Web Storage are intended to solve two cases that "not handled well by Cookie", they are:

  1. The first is designed for scenarios where the user is carrying out a single transaction, but could be carrying out multiple transactions in different windows at the same time.
  2. The second storage mechanism is designed for storage that spans multiple windows, and lasts beyond the current session. In particular, Web applications may wish to store megabytes of user data, such as entire user-authored documents or a user's mailbox, on the client side for performance reasons.

sessionStorage and localStorage are introduced by W3 in HTML5 to solve problems above, let's begin with a review of how Cookie currently works.

Current HTTP State Storage – Cookie


An HTTP Cookie was a set of key/value pairs which an HTTP web server requests a concrete client browser (i.e. User Agent - UA) to store on client's hard disk, when the UA request to the web server further, UA will wrap all the cookie data within the HTTP request header as long as following conditions are all satisfied:

  1. The cookie data has not expired.
  2. The requested domain is under exactly the same domain when cookie was stored.
  3. The requested path under the domain is the same one where cookie was stored.

Once the cookie expires, browser will delete it from local hard disk.

A common cookie example:

  1. An end user types www.foo.net in a browser's navigation bar and hit enter.
  2. www.foo.net returns HTTP status 200 message below (In the Green part, web server expected client browser to store two Cookie key/value pairs: WayneKey1=value1;WayneKey2=Value2, they could be accessible from the entire domain, and they will expire after 1 year):

    HTTP/1.1 200 OK
    Content-type: text/html
    Set-Cookie: WayneKey1=value1;WayneKey2=Value2;domain=www.foo.net; expires=Tue, 24-Feb-2012 07:13:22 GMT; path=/; HttpOnly
    (Response HTTP body)

View Post»


Significant Enhancement in Internet Explorer 9

Written by Wayne Ye  Friday, February 18, 2011


Microsoft announced Internet Explorer 9 Release Candidate on  Feb 10th, 2011, RC indicates except bug fixing, there would not have big changes before the final RTM. Since I've been keeping a watchful eye on IE9 from its very first preview version, I would like to write a post about its significant enhancement from a developer's point of view, I intend to summarize most significant enhancement points of IE9 listed below:

  • Enhanced performance
    1. The New Chakra JavaScript Engine
    2. Hardware Acceleration
  • Enhanced Web Standard Support
    1. HTML5 (huge number of new attributes support and Web Storage support)
    2. CSS3 (border-radius, ::selection pseudo-element, )
    3. W3 standard Geolocaltion API
  • Windows 7 Integration
    1. Website customizable TaskBar Jumplist.

By achieving new features above, IE9 will absolutely be the fastest and best Web Standard support version in the entire IE history.  

Walk through IE9 Enhancements

New JavaScript Engine – Chakra

IE9 team must be persistently working so hard on improving Chakra's performance, I picked following two paragraph  from Chakra Page on Wikipedia:

Microsoft's development of the engine was in response to evolving competing browsers, on which IE8 was lagging behind in terms of JavaScript processing speed.[3] SunSpider tests performed on November 18, 2009 showed the PDC version of IE9 executing scripts much faster than IE8, but slower than respectively Firefox 3.6, Chrome 4, and WebKit Nightly.[4] The same test performed on March 15, 2010 showed the first IE9 Platform Preview (using the then-current version of Chakra) to be faster than Firefox (with SpiderMonkey), but slower than respectively Safari (with SquirrelFish Extreme), Chrome (with V8), and Opera (with Carakan)

On February 8, 2011, the test showed the IE9 Release Candidate (using the current version of Chakra) to be faster than Safari, Firefox (with TraceMonkey), Opera, and Chrome.

View Post»


HTML is the new HTML5

Written by Wayne Ye  Monday, January 24, 2011

Few days ago Ian Hickson wrote a blog: HTML is the new HTML5, he referred "we moved to a new development model", and comes with two major changes:

  1. The HTML specification will henceforth just be known as "HTML", with the URL http://whatwg.org/html.
  2. The WHATWG HTML spec now became "living standard", "It's more mature than any version of the HTML specification". I took a screenshot below:

HTML Living Standard

In a simple sentence: HTML is going to "unversioned model", according to this there is definitely a concern: OK, living standard? Does this mean the standard could be changed/updated/revised at anytime? I saw one person asked posted this question and Ian Hickson replied, he emphasized WHATWG worked hard on backward-capability, and they worked tightly with browser vendors to make sure they do not change things that most people depend on, this is good and really important!

So, things is getting more and more interesting with HTML 5 (should I just call HTML?), few days

View Post»