The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.

Tips & Tools for Creating Interactive Web Application

Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by igodigital, 2017-04-19 14:00:21

HTML5 Hacks

Tips & Tools for Creating Interactive Web Application

Keywords: html5,hack,tools,tips,interactive,web,applications

pack: 'center'

}
}),

initComponent: function() {
//put instances of cards into app.views namespace
Ext.apply(robodeck.views, {
Home: new robodeck.views.Home(),
});
//put instances of cards into viewport
Ext.apply(this, {
items: [
robodeck.views.Home
]
});
robodeck.views.Viewport.superclass.initComponent.apply

(this, arguments);
}

});

Finally, in the app/app/views directory, we’ll open Home.js, where we will define our

own custom xhr() function and call it from within the click handler of our two custom

buttons, Forward and Back.

var server = 'http://' + document.location.host;

function xhr(url) {
var request = new window.XMLHttpRequest();
request.open('GET', url, true);
request.send();

}

robodeck.views.Home = Ext.extend(Ext.Panel, {
...

items: [
{
xtype: 'button',
text: 'Forward',
handler: function(){
console.log('pressed -- Next');
xhr(server + '/next');
}
},

CHAPTER 9: HACKING HTML5 CONNECTIVITY 433

{
xtype: 'button',
text: 'Back',
handler: function(){
console.log('pressed -- Back');
xhr(server + '/back');
}

}
],
...
});

And that’s really all we need to send XMLHttpRequests at the click of a button within

our Sencha 2 mobile application.

Finally, remember the routes we set up in the beginning of this hack to accept the
requests to the URLs http://localhost:3000/next and http://localhost:3000/back?
Now we can make use of them. Once the request is received, we trigger a web socket

send() method:

app.get('/next', function(req, res) {
send(JSON.stringify({ "cmd": 'next' }));

});

app.get('/back', function(req, res) {
send(JSON.stringify({ "cmd": 'prev' }));

});

In our connected clients we listen for the message, and if it has a cmd property we
dynamically call that command from the $.deck object:

socket.on('message', function (data) {
var json = JSON.parse(data);
...
if (json.cmd) {
console.log('cmd: ' + json.cmd);
console.log("CMD MESSAGE");

// call deck.js api
$.deck(json.cmd)
}
...
});

All connected clients should see the move forward and backward, given the button
clicks of the mobile remote application.

434 HTML5 HACKS

HACK 77 Inspect a Socket.IO Connection to
Determine If It Is Native or Emulated

Chrome Developer tools can help with debugging network traffic. You can also disable
web sockets to demonstrate the power of Socket.IO polyfills.
In this hack we’ll investigate the power of Socket.IO. Earlier, I explained that Socket.IO
provides the ability to polyfill socket support for browsers that don’t have a socket
implementation enabled yet. In previous hacks we used the Chrome Developer Tools
to inspect WebSocket information.
One way to test the ability of Socket.IO to fall back to another mechanism is to go into
the Chrome Dev Tools console and enter WebSocket = undefined (see Figure 9-42).

Figure 9-42.
Turning off WebSocket support in Chrome

Then, if you click in the Network tab, you’ll notice that the browser has closed the
WebSocket connection and fallen back to XHR-polling. You will see HTTP requests
being sent on regular intervals to check for any updates (see Figure 9-43).

HACK 78 Build a Simple SPDY Server with
node-spdy

SPDY is a protocol created and used by Google to reduce web page load time. It doesn’t
replace HTTP; rather, you can use it to compress and simplify HTTP requests.
Let’s start this hack with a disclaimer: this hack will be short and simple. An exploration
of SPDY is simply too large for this book. Besides, we have already exceeded 400
pages!
That being said, SPDY is too important to the future of web technologies and the
HTML5 connectivity layer to not be mentioned.
So, the goal of this hack will be to get you up and running with the very basics of SDPY,
and add another tool to your tool belt.

CHAPTER 9: HACKING HTML5 CONNECTIVITY 435

Figure 9-43.
XHR-polling polyfill from Socket.IO

node-spdy

To serve up our simple SPDY implementation we will default to Node.js as we often
have throughout this text. We will make use of Fedor Indutny’s node-spdy.
You can pull down the hello_world example from GitHub.

Let’s go ahead and git clone the entire directory, and then navigate to the

hello_world example:
$ cd your-code-directory

$ git clone git://github.com/indutny/node-spdy.git

Now we’ll navigate into the directory and run npm install:

$ cd node-spdy
$ npm install
Now we can start our SPDY server:
$ node app.js
We are up and running on port 3232.

436 HTML5 HACKS

Let’s navigate to https://localhost:3232/, and we should see “Hello World” (see
Figure 9-44). Be sure to include the “https://” in the URL, or your request will not be
accepted.

Figure 9-44.
Simple “Hello World” from node-spdy

We made a simple request, and the server responded with “Hello World.” You are not
going to see a major improvement to your response because it is just too simple.

SPDY shines when you use it with applications that make a large number of connec-
tions and transfer significant amounts of data. The string “Hello World” hardly falls
into that category of applications.

What’s Next?

Well, that’s it. I warned you in the disclaimer. This should be enough to get you started.
Try adding some logic that creates an abnormal number of requests or passes large
payloads. Hook up a performance tool and see if you can tell the difference. Stay tuned
in the html5hacks.com/blog for updates on SPDY.

CHAPTER 9: HACKING HTML5 CONNECTIVITY 437



10

Pro HTML5 Application Hacks
with Node.js

Up to this point, this book has provided a sample collection of hacks that cover a large
portion of the HTML5 feature suite. But what about building professional HTML5 ap-
plications?

As you can see in the latter chapters of the book, some of the HTML5 specifications
are advancing the technologies at the connectivity layer. In order to begin creating
hacks that examine those specifications, we need to employ a web server. We also
want to be able to write our markup quickly and deploy our changes easily. The Node.js
tool set makes these concepts simple and easy to learn. Node.js is also written in
JavaScript, so we can use the same programming language in both the browsers and
the server.

It is certainly arguable that other programming languages and web frameworks, such
as PHP and Ruby on Rails, provide similar environments, but for the purposes of cre-
ating “quick and dirty” hacks to exercise new HTML5 APIs, there is no better choice
than Node.js.

The hacks in this chapter will guide you all the way through to having an HTML5 boil-
erplate starter app that can be easily deployed to a remote server. If you so desire,
you can even skip ahead to the final hack and download a starter kit for building pro-
fessional HTML5 applications in Node.js.

HTML5 Application Design Considerations

In addition to providing hacks that teach you the basics of using these cutting-edge
tools, this chapter will also touch on some of the most common modern HTML5 ap-
plication design challenges presented to developers today, including considerations
for the mobile web, client-side performance optimizations, cross-browser compati-
bility, and DRYing (Don’t Repeat Yourself) up your code base.

439

Why Node.js?

First, let’s start with one of the most hyped technologies of late, Node.js. We didn’t
select this server for the hype surrounding it. We selected it for the following key
reasons:

• Node.js provides an HTTP server, so we can serve files.
• Node.js also exposes a JavaScript API, so we can use the same programming

language on the server and client to build applications.
• There are a number of tools that make deployment of Node.js apps simple and

fast. Since our goal is to create hacks, we will leverage as many of these tools as
possible.

Installation

I won’t go into great detail on how to install Node.js. For a local setup, just go to http://
nodejs.org/#download to download an installer.

If you want to install via a package manager go to https://github.com/joyent/node/
wiki/Installing-Node.js-via-package-manager.

The official documentation for installation, given the specifics of your local environ-
ment, is available at https://github.com/joyent/node/wiki/Installation.

Once you have installed Node.js, open a terminal and check your installation.

Installing on Mac OS X via Homebrew

If you are using a Mac, perhaps the easiest way to get up and running quickly is to
install via Homebrew. Once you have Homebrew, installation is as simple as running
the following:

brew install node

user$ node -v
v0.4.7

HACK 79 Deliver “Hello Html5” to the Browser

With this classic “Hello World” hack you’ll be able to use Node.js to handle requests
from browsers and respond with content.

Let’s get a handle on our first HTTP request and response with Node.js. We’ll start as
simple as possible: we’ll use the example “Hello World” application from nodejs.org.

440 HTML5 HACKS

To get started, we only need to navigate to an empty directory within our filesystem
and create an empty file, such as server.js.

We’ll add the following to the file:

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Html5\n');
}).listen(1337, "127.0.0.1");

console.log('Server running at http://127.0.0.1:1337/');

Now we can execute the code with the file by running the following from the command
line:

$node server.js

Let’s walk through what is going on here. At the top of the file there is a require

method which is part of Node.js’s Dependency Module Management System that fol-
lows the CommonJS specification. Once the HTTP module is included, we can call

http.createServer() and pass it a function that accepts a request and a re
sponse object as parameters. Each object has its own set of methods and properties.

Later, we will examine them a little more closely by logging both the request and the
response to the console.

http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Html5\n');
}).listen(1337, "127.0.0.1");

Here you can see that writeHead() is used to return a response code and write the

contents to a buffer, along with the object that contains the response headers. The

end() method then accepts a string.

The last item to notice here is the listen() method chained onto the end of crea
teServer(). Once createServer() has completed and returned, the next method
in the stack is listen(), which is passed to the port number to listen on. The crea
teServer() method returns an object that inherits the http.Server prototype.

Those are the basics of setting up and running a Node.js server.

Before we print out our request, let’s turn off the logging of the additional request for
favicon.ico, so the console doesn’t print the two requests made from the browser. This
will make our logs slightly easier to read.

var http = require('http');
http.createServer(function (req, res) {

CHAPTER 10: PRO HTML5 APPLICATION HACKS WITH NODE.JS 441


















































































Click to View FlipBook Version