HTML5 Enhancements

1. Web Storage

As per the standards prescribed in HTML5, the browsers should store data locally termed as web storage, similar to traditional cookies. But this web storage is much more secured and data retrieval is much faster as:
  1. The data is stored as Name-Value collection, hence retrieval is faster.
  2. Data stored by one web page can only be accessed by the same page and also when the page is accessed using the same browser. For instance, data stored through Chrome can’t be accessed by Internet Explorer even from the same HTML page thus providing security.
The other benefit is the ability to store large data without even affecting the web application’s performance. There are two flavors of this storage:
  1. Local Storage (localStorage) - There is no expiry date for the data stored, i.e., the data won’t be deleted after the browser’s close event, i.e., even after the browser is closed.
  2. Session Storage (sessionStorage) - The data stored is driven by the session, i.e., it is available for the browser session in concern only.
These storages could be leveraged when there is a need to remember what user has entered in different textboxes even after browser reopening or refreshing. This requirement could have been achieved using traditional cookies but web storage provides better accessibility and security as mentioned earlier.
In supported browsers, we may access the web storages as:
localStorage.employeeId = 25771; -> for storing the value
var empId = localStorage.employeeId; -> for retrieving the value
Where ‘employeeId’ is a user defined key in the web storage.
Similarly based on need, one may use sessionStorage in place localStorage.

2. Editable Content

Using this feature in the supported browser, one can make the text content in HTML element editable. This can be applied to any elements expected to hold text using a new attribute – ‘contenteditable’ by setting it to ‘true’. Once applied, all the text content in the element including even the child element will become editable. This internally makes use of the web storage explained in the earlier section.
It could be used in an application where one needs to provide an option to edit any content (text) in any specific part of the page. This same could be have been implemented by multiple use of ‘input’ elements of type ‘text’, but then the implementation would be complex and would in turn affect maintainability or future enhancements.
<ul contenteditable="true">  
        <li> Code for Home Page </li>  
        <li> Code for Browse Page </li>  
        <li> Code for Mystuff page </li>  
</ul>
So the texts in the different <li>s become editable. E.g. To-do list implementation.

3. Scalable Vector Graphics (SVG)

SVG is an XML based language for describing 2D graphics/images. These SVG based XML contents can be provided in two ways:
  1. Using an external file (.svg) and then embedding in the main page HTML page using elements like<embed>, <object>, or <iframe>.
  2. It can be also embedded in the HTML page using the <svg> element. E.g.:
<!DOCTYPE html>
<html>
<body>
 
<svg xmlns="http://www.w3.org/2000/svg" 
version="1.1" height="190">
   <ellipse cx="200" cy="100" 
   rx="70" ry="70" fill="red">
</svg>
 
</body>
</html>
The above markups will print a red colored ellipse in the supported browser.
It has a lot of advantages over other 2D graphics creation approaches like ‘canvas’, to list a few:
  1. Since this is XML based hence the image can be edited using any text editor
  2. Its quality doesn’t get compromised when the image is zoomed in
  3. Doesn’t involve any complex client side Java scripting
  4. Since it is text based, it eases image searching and indexing
  5. Independent of resolution and hence high quality images can be printed
Disadvantage is, since it is XML based, like any DOM object, its rendering is comparatively slower compared to other graphics creation approaches like canvas, etc.

4. Email, URL Inputs

Now the ‘input’ element provides out–of-the-box validation for its content. For example, by specifying ‘type=email’ or ‘type=url’, we can restrict the content text to be compliant with valid email address or URL structures.
Though it simplifies the developers' work like validation for content, but currently is not supported across all browsers. So unless there is clear cut understanding or if there is restriction to the type of browsers for your client application, one should avoid using it. If the browser doesn’t support the property, the behavior would be like regular textbox, i.e., ‘input’ element of type ‘text’.

5. Server Sent Events (SSEs)

‘Server sent event’ is basically intimation from the server to the client when there is a need, i.e., the server will send data to the client without requiring the client to demand for it. In the traditional approach, the client keeps polling the server for data and this result in greater HTTP overhead. With these events, the server intimates the client with data whenever available without even initiating the request from the client.
Thus a one way messaging channel is opened between server and client and this is handled by the browser directly, the user just listens for message. The browser will take the burden of keeping the connection to the server open using the JavaScript object EventSource. The client needs to just register to events like ‘onopen- connection to the server established’, ‘onmessage- message received from server’ and ‘onerror-when error occurs’ on this object.
At the client side:
var evtSource=new EventSource("url of the page raising the events");
evtSource.onmessage=function(e)
  {
                //handle the e.data as appropriate
  };
At the server side:
We need to make sure that:
  • the HTTP response content type should be “text/event-stream
  • the response content should always start with ‘data: 
Response.ContentType="text/event-stream"
Response.Write("data: " + <data to be passed to the client>)
The SSE could be best leveraged in one way communication scenarios like RSS feed. For duplex communication however, HTML5 Web Sockets API may be explored.

6. Types for Scripts and Links are Not Needed

The tags namely ‘script’ and ‘link’ need not have ‘type’ attribute explicitly mentioned. These tags are now provided with implicit meaning. For example, earlier to HTML5, we used to include these tags as:
<script type="text/javascript" 
src="path_of_some_javascript.js"></script>

<link type="text/css"  rel="stylesheet" href="path_of_some_stylesheet.css" />
Going forward, there would not be any need to provide ‘type’, just the following entries are enough to understand that the tags are for script and style-sheet respectively:
<script src="path_of_some_javascript.js"></script>
<link rel="stylesheet" href="path_of_some_stylesheet.css" />

7. Web Workers

Web workers are like a daemon service running in the background in the browser instance without affecting the performance of the web page. This could be leveraged for high CPU intensive operations.
In the traditional approach, the page gets blocked until the execution of the script is completed. Using web worker which is a JavaScript in external js files, we may get rid of this issue as this script will run in the background without affecting the execution of other scripts and events like button click, etc.
For example, let’s consider a JavaScript which fetches ‘message’ dropped by users of an online messenger application like Gtalk. Let’s keep this in an external js – message.js as:
function BroadcastMessage()
{
var message = new message();

//here, get the messages dropped by users and assign it to ‘message’ object
//then raise the postMessage passing the ‘message’ object

postMessage(message);

setTimeout("BroadcastMessage ()",500);  //keep broadcasting the messages after a fixed interval indefinitely.
}

BroadcastMessage();
The client for this js would be like:
var w =new Worker("message.js");

w.onmessage = function (e) {
// read the message from e.data object

//and show as needed
};
Thus the BroadcastMessage will keep running in the background without affecting the front end activities like button click, etc. Implementation of any online-chat application may adopt this approach.

8. Figure Element

HTML5 provides a way of associating caption with an image using ‘figure’ and child ‘figcaption’ elements. These elements help in grouping the illustrations, photos, etc. in a single unit which is self-contained. This eases the handling of the unit without affecting the main flow of the document. There is not much difference in terms of the look, but provides a semantic approach of grouping the image and the associated caption.
<figure>   
    <img src="location of the image"/> 
    <figcaption> 
        <p>a description probably depicting the image goes here</p> 
    </figcaption> 
</figure>

9. Application Cache

This is an important tool to enable the offline browsing of any web application. This makes use of a cache manifest file (.appcache) which basically guides the browser regarding which all files to be cached and which all not to be cached using the following sections:
  1. CACHE MANIFEST – It has the list of files which will be cached at the client once these are downloaded for the first time.
  2. NETWORK- The files will not be cached and would require connection to server.
  3. FALLBACK- It is like comprising the behavior of both the above headers. For each file or type, specify the fallback page which will be used if the original page is not accessible, i.e., not online.
Example of manifest file content:
CACHE MANIFEST
 /style.css
 /favicon.gif
                NETWORK:
                                Home.aspx
                FALLBACK:
/html/ /page_not_found.html 
i.e., if any HTML is not found, then the default page_not_found.html will be displayed.
And then, include the manifest file in the main HTML page as:
<!DOCTYPE HTML> 
<html manifest="manifest_filename.appcache">
 ... 
</html>
This serves the following benefits:
  1. Offline browsing capability
  2. Improves the page load
  3. Only updated or changed files would be downloaded and hence improves the network bandwidth usage

10. Datalist Element

This is a new type of element prescribed in HTML5 standard. This is used in conjunction with ‘input’ element to depict a predefined list of values. For example, with the new ‘list’ attribute provided for ‘input’ and the associated ‘datalist’ element, if one tries to type something in the text-box, the matching options will be shown as drop down in the supporting browsers. E.g.:
<input list="countries" name="country">
<datalist id="countries">
  <option value="India">
  <option value="Indonesia">
  <option value="USA">
  <option value="UK">
</datalist>
So irrespective of the case if one inputs ‘i’, India and Indonesia will get listed as dropdown.

11. Geolocation

Geolocation interfaces could be used to get the user’s geographical location. It may be best leveraged in GPS enabled devices to correctly get the latitudes and longitudes. And once these data are received, using the same one may pin point to the exact physical location with application like Google maps, Bing maps. The kinds of application where this could be used are:
  1. Path finder providing the turn by turn navigation
  2. Places of interest like ATM, restaurant, gas station, etc. near the user, etc.
Script to get the user’s latitude and longitude:
navigator.geolocation.getCurrentPosition(GetPosition);
function GetPosition (pos)
 {
$('#lbllocation').html("Your Latitude: " + pos.coords.latitude +   "

Your Longitude: " + pos.coords.longitude );
}

12. Required Attribute

Like the ‘email’ and ‘url’ types for ‘input’ element/tag, this attribute is meant to ease data validation burden. This is used either providing a standalone attribute ‘required’ or as key-value pair like required="required". Once applied on any input of type –text and if without providing any data, the main form is tried to be submitted, the supporting browser will highlight and stop the form submission.
<input type="text" name="lastName" required>
Or:
<input type="text" name="lastName" required="required">

13. Autofocus Attribute

Like ‘required’ attribute discussed above, this may be also applied just by providing a standalone attribute ‘autofocus’ or as key-value pair like autofocus ="autofocus ". And as name depicts, this helps in auto focusing or auto selecting an element by default when the page gets loaded.
<input type="text" name="employeeId" 
placeholder="Employee Id here" required autofocus>
Or:
<input type="text" name="employeeId" 
placeholder="Employee Id here" required autofocus=”autofocus”>

14. Support for Regular Expressions Pattern

Again a nice way to validate the content of input element for a specific pattern without writing complex JavaScript. Using new HTML5 suggested ‘pattern’ attribute for input element, we may directly provide the regular expression in the markup itself. If the text in the input element doesn’t comply with the expression, the browser will highlight the control.
<input type="text" name="lastName" 
placeholder="Last Name here" required autofocus pattern=”[A-Za-z]”> 

15. Drag and Drop

Drag and drop is also a trivial requirement but we know the amount of code and effort needed in the traditional approach. In HTML5 standard, any element can be “draggable” by providing the attribute-draggable="true”. One needs to just provide the implementation for the event:
  • ondragstart (to set the data to be dragged) on the element from where some data is dragged
  • ondrop (to handle the data which is dragged) on the element where the data is dropped
The element to be dragged:
<img id="img1" src="some_image.gif" draggable="true" 
   ondragstart="drag(evt)" width="300" height="50">
Container to which the dragged data will be dropped:
<div id="div1" ondrop="drop(evt)"></div>

16. Audio Element

Until now, to support an audio file in a web page, we had to depend upon third party provided plug-ins (like Flash player). HTML5 now provides standard for playing audio files:
<audio autoplay="autoplay" controls="controls">   
    <source src="audio1.ogg" /> 
    <source src="audio1.mp3" />  
    <a href="audio1.mp3">Click here to download the mp3.</a> 
</audio>
As HTML5 specification doesn’t specify any standard for audio formats, to keep the implementation compliant with different browsers and across different versions for the same browser, it is always suggested to have ‘source’ with more than one format. The browser will pick up the first format it understands. It is also suggested to keep some message within the ‘audio’ element so that for non compliant browsers, this message will be shown depicting that this audio element is not supported, e.g.:
<audio autoplay="autoplay" controls="controls"> 
    <source src="audio1.ogg" /> 
    <source src="audio1.mp3" />  
    Your browser doesn’t have support for HTML5 ‘audio’ element 
</audio>

17. Video Element

Like audio, for video also, until now we were required to depend upon external plug-ins like flash player, there were no HTML standard and different browsers had support for different plug-ins. HTML5 now provides a standard for playing video files as well. All the good practice mentioned above for audio elements holds good for video elements:
<video width="300" height="200" controls preload id=”vd1”>
                <source src="movie1.mp4" type="video/mp4">
                <source src="movie1.ogg" type="video/ogg">
                Your browser doesn’t have support for HTML5 ‘video’ element 
</video>
But not all codecs are supported by all browsers. Some support H.264, other Theora and Vorbis, etc. HTML5 specification doesn’t specify any specific codec for video formats.
For both audio and video elements, HTML5 specifies DOM methods, properties and events which may be customized using JavaScript. For example:
There are methods to programmatically play, pause, etc.
var vElement=document.getElementById("vd1");
function playVidio()
  {
                vElement.play();
  }
function pauseVidio()
  {
                vElement.pause();
  }
Here, vd1 is the video element. These methods namely playVIdeo and pauseVideo can then be invoked from buttons’ click events.
There are properties like autoplay, volume, duration, etc. e.g.:
var vElement=document.getElementById("vd1");

vElement.autoplay=true; //thus plays the media as soon as it is loaded
There are events to tell the start of action like canplay, play, pause, etc. e.g.:
var vElement=document.getElementById("vd1");
//a message will be shown once the browser is ready to play
vElement.oncanplay=alert("Browser can play the media"); 

18. Slider Control Using Input Element of type- range

This is also a trivial UI requirement where we need to display a sliding bar depicting the completion/stage of certain operation. HTML5 prescribes the new range type for input element.
<input type="range">
It has support for additional attributes like min, max, step and value. We may even add event listener to develop user driven slider similar to those of volume control, etc.
<input name="rngElement" type="range" min="0"
max="100" step="5" value="">

19. Mark Element

Mark element is like a highlighter. For example, if we want to highlight a part of the following text, then we may achieve the same using ‘mark’ as:
<p> The quick brown fox jumps right over the <mark>lazy dog</mark>.
</p>
But in the supported browsers ‘mark’ has different styles so, to achieve consistent behavior, we need to provide the corresponding style definition like:
mark {
   background-color: #fff;
   font-weight: normal;
   font-style: normal;
   color: red;
 }

20. Custom Attribute by Prefixing ‘data’

Now with HTML5, there is official support for custom attribute for any element. Though earlier some browsers did have support for user defined attribute like:
<input type="text" id="input1" required customAttribute = ‘abc’>
But this was not evenly supported in all browsers. But now with HTML5 recommendation, we may have something very similar across all the supporting browsers. The only requirement is, we need to prefix our custom attribute with the word- ‘data’ and we are good to go.
<input type="text" id="input1" required data-customAttribute = ‘abc’>

Some of the Ways to Understand If the HTML5 Specific Attributes/Elements are Supported or Not

Now that we have learnt quite a few interesting and helpful enhancements in HTML5 standard, it is very important to know that at present, not all enhancements are supported in all the browsers and we should be very careful while using them.
Here, we will see some of the ways in which we may conclude whether the concerned enhancement is supported in the browser being used or not.
  1. For example, to understand if ‘pattern’ attribute is supported for input element or not, we may dynamically create a ‘input’ element and then try looking for the attribute in it:
    <script> 
    if (!'pattern' in document.createElement('input') ) { 
        // then the ‘pattern’ attribute is not supported 
        // hence need to provide the traditional approach
    } 
    </script>
  2. To check for any HTML5 specific element or object, e.g. audio, EventSource, etc.
For element:
var  frm = document.forms[0];
If(typeof( frm[‘element_name’]) == undefined){
//then the element is not supported
}
Example of element_name could be ‘audio’, ‘video’, etc.
Similarly for object (e.g. EventSource):
If(typeof(EventSource) == undefined){ 
                //then the server-sent event is not supported

}

Conclusion

So by now, we are acquainted with quite a few new enhancements prescribed in HTML5 and also learnt how to use these. But it is worth mentioning that not all browsers are adapting to these standards or enhancements at the same pace. So if we want to make our website consistent across all the browsers and in fact across all the versions of different browsers, we need to always make sure that we provide the fall back approach. That is, if any specific element, attribute, etc. are not supported, then provide an alternate approach to handle it traditionally.

No comments:

Post a Comment

Genuine websites to earn money.

If you are interested in PTC sites then this article is for you. I have personally tried many of the sites and found that the best thing ...