APIs: Overview - JUMP START HTML5 (2014)

JUMP START HTML5 (2014)

Chapter 26 APIs: Overview

In this chapter, we’ll make a quick trip to the world of HTML5 APIs. I’ll outline the APIs that are going to be discussed in this book, and what you’ll have learned by the end. There’ll be no diving into any code in this chapter; rather, it will provide a quick overview of each API so that you can get a clear idea about what you’re going to learn.

Some HTML5 APIs are still fairly new, and not every version of every browser supports them, which you’ll need to bear in mind while creating HTML5 apps. Whenever you’re going to use any HTML5 API, it’s always a good idea to check the support for that API in the browser. We’ll see how to do that in the last section of the chapter.

A Quick Tour of the HTML5 APIs Covered

Since this is a short book, it’s impossible to cover each and every API. Some APIs are already covered in other books in SitePoint’s Jump Start HTML5 range. In this book we’ll focus on five important JavaScript APIs that you can use to create really cool web apps. (Yes, web apps built with plain HTML5 and JavaScript! How cool is that?) So, let’s see what we’ll be discussing:

· The Web Workers API: Ever thought of bringing multi-threading to the Web? Have you every fancied performing some ongoing task in the background without hampering the main JavaScript thread? If yes, it’s probably time for you to get cozy with the Web Workers API because it’s designed just for this purpose.

o Formal definition: The Web Workers API is used to run scripts in a background thread that run in parallel to the main thread. In other words, you can perform computationally expensive tasks or implement long polling in the background and your main UI thread will remain unaffected.

· The Geolocation API: This new API simply lets you know where your users are. It enables you to find the position of your users—even when they are moving. Furthermore, you can show them customized choices (maybe a nice café or a theater near them) depending on their location, or plot their position on the map.

o Formal definition: The Geolocation API lets your application receive the current geographical position of the user through simple JavaScript.

· The Server-sent Events API: The way Facebook pushes new updates to your wall is awesome, isn’t it? Prior to the introduction of Server-sent Events (SSE, for short) this type of functionality was achieved using long polling. But with the all new SSEs, the server can automatically push new updates to the web page as they become available. You can access those updates in your script and notify your users.

o Formal definition: The Server-sent Events API lets your clients receive push notifications from the server without the need of long polling.

· The WebSocket API: This API helps you build applications that allow bi-directional communication between client and server. The classic use case of the WebSocket API is a chat application where a client sends a message to the server and the server processes it and replies back!

o Formal definition: This API enables low-latency, full-duplex single-socket connection between client and server.

· The Cross-document Messaging API: Because of dreaded CSRF attacks, documents from different domains are usually not allowed to communicate with each other. But with this new Cross-document Messaging API, documents from different origins can communicate with each other while still being safe against CSRF.

o Formal Definition: This API introduces a messaging system that allows documents to communicate with each other—regardless of the source domain—without CSRF being a problem.

Note: Cross-site Request Forgery (CSRF)

CSRF is a type of attack that tricks end users to perform sensitive operations on a web application without their knowledge. Typically, websites only verify if the request is coming from the browser of an authenticated user, but they don’t verify if the actual authenticated user himself is making the request. That’s the common cause of a CSRF attack.

To learn more about CSRF attacks, please visit the Open Web Application Security Project.

What You Are Going to Learn

This book will provide clear and concise explanations of the APIs just mentioned. You will learn the purpose of each API and how to use them. By the end of the book, you’ll be able to create cool and exciting apps using some amazing HTML5 features.

While explaining the APIs, I will provide some code snippets that describe the general working principle of them. Since this is a short book, it’s impossible to cover everything exhaustively, but I will try to cover as much as possible in each chapter. I’ll also provide guidance and share example use cases for each of the APIs.

Getting Started

Before diving into the world of HTML5, there is a caveat of which to be aware. As mentioned, some HTML5 APIs are quite new so you should always make sure the specific feature is supported in the browsers. If there’s no (or limited) support, you should handle it gracefully by falling back to another technique. This is known as graceful degradation; in other words, your app is designed for modern browsers but it is still functional in older browsers. On the other hand you could also opt for progressive enhancement techniques, where you create an app with limited functionalities and add new features when the browser supports them. For more information on this, have a look at Craig Buckler’s article on sitepoint.com.

In this section, we will discuss addressing the browser compatibility issues and setting up the development environment.

Checking Browser Compatibility

It’s always good to obtain an overview of the list of HTML5 features supported by the browsers. Before using any API, refer to a compatibility chart that shows which browsers support that API. Personally, I prefer caniuse.com where you just start typing the name of the API and it shows the browser versions that support it; however, although a compatibility chart gives an overview, you should always check for browser compatibility of API features in your JavaScript code.

Each HTML element is represented by an object inside the DOM, and each object has several properties. So, in browsers that support HTML5 APIs, certain objects will have a set of unique properties. This is the key to determining the browser’s support for various HTML5 features.

Support for some HTML5 features can be detected just by checking the existence of certain properties on the window or navigator objects. For example, you can write the following code to check the support for Web Workers:

if(!!window.Worker){

//proceed further

}

else{

//do something else

}

As you can see, in Web Worker-enabled browsers there will be a property called Worker in the window object.

Similar techniques can also be used to detect the support for other features. We will see how to detect each feature when we examine the details of each API.

Modernizr

Wouldn’t it be great if there was a uniform interface for checking the support for each API? Well, it just so happens there is an open-source JavaScript library that helps detect HTML5 features: Modernizr.

Using Modernizr is a matter of downloading the script and adding the the following code to the <head> element:

<script type="text/javascript" src="modernizr.min.js">

Note: Always put Modernizr in Your <head>

Just make sure to load the Modernizr script in the <head> section. The reason is because the HTML5 Shiv, which enables the styling of HTML5 elements in browsers prior to IE9, must execute before the body loads. Also if you are using Modernizr-specific CSS classes, you might encounter an FOUC (flash of unstyled content) if the script is not loaded in the <head>.

Now, let’s say you want to detect the support for Web Workers in the browser. The following snippet does that for you:

if(Modernizr.webworkers){

//proceed further

}

else{

//no support for web workers

}

So if the browser supports webworkers, the Modernizr.webworkers property will be true. There are similar tests for all other features. We’ll be using Modernizr in this book to check for browser compatibility.

Setting Up the Environment

To create HTML5 apps, you only really need your favorite text editor and browser. But to use certain APIs such as Server-sent Events and WebSocket, you will need a server. So I’ll ask you to install WAMP or XAMPP on your machine so that we can easily create a local server to try things out. If you already have a server set up, you’re good to go.

In this chapter, we discussed the list of APIs covered in the book and learned how to detect browser support for each HTML5 feature. We also discussed the purpose of each API in brief and finally set up our development environment.

I know you’ve been waiting to get your hands dirty. Now that you’re aware of all the basic stuff, let’s start our journey into the world of HTML5 APIs, with Web Workers being the first place to visit.