Hi I would like to share my knowledge on HTML5 and also it would be helpful for you to prepare some rich applications using HTML5.HTML5 has introduced many new tags and
also many new features which would help internet become more fast but having said that not all browsers support HTML5
only likes of google chrome,mozilla firefox 3.5 and above,safari 4 and above,opera 10.5 and above and IE9 support most of the HTML features.
and also there is still time left for HTML5 to be a standard as fewof its features are still in development phase
and extension of manifest is not fixed yet either it would be .appcache or .manifest so still there remains a time but
what all features are in market makes it a good way to browse internet faster
People can be forgiven for assuming that awesome JavaScript-less transitions are grouped into the all-encompassing HTML5. Hey — even Apple has inadvertently promoted this idea. For non-developers, who cares; it’s an easy way to refer to modern web standards. However, for us, though it may just be semantics, it’s important to understand exactly what is not HTML5.
SVG: Not HTML5. It’s at least five years old.
CSS3: Not HTML5. It’s…CSS.
Geolocation: Not HTML5.
Client Storage: Not HTML5. It was at one point, but was removed from the spec, due to the fact that many worried that it, as a whole, was becoming too complicated. It now has its own specification.
Web Sockets: Not HTML5. Again, was exported to its own specification.
Regardless of how much distinction you require, all of these technologies can be grouped into the modern web stack. In fact, many of these branched specifications are still managed by the same people.
There are many tags introduced in HTML5 which wouldn't had require like article,section,mark,header,footer but they basically designed for search engine optimization ie
you should specify certain content of your page within this tags so that when ever a content to search is typed search
engine automatically goes to a particular tag and then searches the content in that part of the tag instead of whole page.Thing to note here is that we can test whether that specfic tag is supported by a browser or not by specifying a (fallback)content in between tag and if that content is visible then it means that the browser doesn't support the tag.
Few Examples
<style>
[required] {
border-color: #88a;
background:red;
}
:invalid {
border-color: #e88;
background:red;
}
</style>
<input required="true" type="text" /><input type="text" required />
<input value="some@email.com" type="email" /><input type="email"
value="some@email.com" />
<input min="2010-08-14" max="2011-08-14" value="2010-08-14" type="date" /><input
type="date" min="2010-08-14" max="2011-08-14" value="2010-08-14"/>
<input min="0" max="50" value="10" type="range" /><input type="range" min="0"
max="50" value="10" />
<input results="10" placeholder="Search..." type="search" /><input type="search"
results="10" placeholder="Search..." />
<input placeholder="(555) 555-5555" pattern="^\(?\d{3}\)?[-\s]\d{3}[-\s]\d{4}.*?$"
type="tel" /><input type="tel" placeholder="(555) 555-5555"
pattern="^\(?\d{3}\)?[-\s]\d{3}[-\s]\d{4}.*?$" />
<input placeholder="e.g. #bbbbbb" type="color" /><input type="color"
placeholder="e.g. #bbbbbb" />
<input step="1" min="-5" max="10" value="0" type="number" /><input
type="number" step="1" min="-5" max="10" value="0" />
Apart from search engine optimization there are also few types introduced in few tags like for input tag
types like email,url,color which actually checks whether the specific input is a email id or a url
and hence it validates automatically and also there is a list attribute introduced in input tag which provides automatic
suggestions for a textbox about what all inputs you can put for that box
eg code:-
CAR:-<input list="car"/>
<datalist id="car">
<option value="Q7"></option>
<option value="Q5"></option>
</datalist>
AUDIO
No longer do we have to rely upon third party plugins in order to render audio. HTML5 now offers the <audio> element. Well, at least, ultimately, we won’t have to worry about these plugins. For the time being, only the most recent of browsers offer support for HTML5 audio. At this time, it’s still a good practice to offer some form of backward compatibility.
<audio autoplay="autoplay" controls="controls">
<source src="good.ogg" />
<source src="good.mp3" />
<a href="good.mp3">Download this file.
</audio>
What happens when you specify two or more types of source elements in audio or video tag is that the browser automatically chooses the specific audio or video type.
VIDEO
Much like the <audio> element, we also, of course, have HTML5 video as well in the new browsers! In fact, just recently, YouTube announced a new HTML5 video embed for their videos, for browsers which support it. Unfortunately, again, because the HTML5 spec doesn’t specify a specific codec for video, it’s left to the browsers to decide. While Safari, and Internet Explorer 9 can be expected to support video in the H.264 format (which Flash players can play), Firefox and Opera are sticking with the open source Theora and Vorbis formats. As such, when displaying HTML5 video, you must offer both formats
<video controls preload>
<source src="good.ogv" type="video/ogg; codecs='vorbis, theora'" />
<source src="good.mp4" type="video/mp4; 'codecs='avc1.42E01E, mp4a.40.2'" />
<p> Your browser is old. <a href="good.mp4">Download this video instead.
</video>
CANVAS
This tag is introduced to kill flash.you can perform any operation on this tag with the help of javascript functions but it is said that it should only be used for some specific operations like we can write text on canvas element but it is better to use a div element instead but if it needed like we making a graph and will have to write a naming convention for that graph then we can do that using canvas or want some decorated text to be written then we can canvas for such purposes.
There are many operations that can be performed on canvas element first is to declare a canvas tag then specify its id attribute and also height and width attributes if they are not specified their default vlaues is set.
<canvas id="mycanvas" height="300" width="300">
This text will appear if canvas element is not supported by your browser<canvas>
Then if we want to perform any operation on canvas element first we have to get its context like
eg:-
var canvas = document.getElementById("mycanvas");
var cxt = canvas.getContext('2d');
Here we have asked for 2d amnimations to be performed on the canvas which is currently available but yes a 3d context is also awaited to make 3d animations.
Every operation is performed on canvas with the help of context object
like eg;-
cxt.moveTo(x,y) >> moves the cursor to the specified location in the canvas element.
cxt.lineTo(x1,y1) >> draws a line from (x,y) to(x1,y1).
cxt.arc(CenterX,CenterY,Radius,Startangle(in Radians),Stopangle(in Radians),
Stroke clockwise(true)or anticlockwise(false));
NOTE:- line will only be visible if cxt.stroke() is mention after lineTo(x1,y1).
Then we can also set various other attributes like
cxt.strokeStyle = "gray"; cxt.lineWidth = 5;
and also there are many more functions available to perform certain actions on canvas.I have attached a file where you can find examples of few tags which help you understand that tag better.
There are also many new tags introduced in HTML5 for more information on tags you can see http://www.w3shools.com
HTML5 features
Now i would like to concentrate on the new features of HTML5
Drag and Drop
Drag and Drop is a new feature introduced in HTML5,its basic use is to copy and paste by draging elements or images in a graphical way and also it could be used
be used while comparing 2 or more things just drag and drop images of things you want to compare in a comparison boxes and you will be able to
see the results.
For this we would be using javascript like
function drag(target,e) {
e.dataTransfer.setData('text', target.id);
}
function drop(target, e) {
var id = e.dataTransfer.getData('text');
target.appendChild(document.getElementById(id));
e.preventDefault();
}
where i have made 2 div elements with attributres like id,ondrop,ondragenter and ondragover where you can specify whatever id you want and ondrop is a event ie when anything is droped on that div element it calls a function drop(this,event) and ondragenter and ondragover are specified as return false this two are important events as they will animate mouse cursor of where can you drop a particular dragable and dropable image or element.
And for the elements which are to be dragged we specify a attribute for them as ondragstart="drag(this,event)".Also note that we have specified
e.preventDefault() this is used because few browsers perform their default operations on drag and drop so inorder to prevent their default action we need to specify this.
Now All drag events have a property called dataTransfer which is used to hold the drag data.
When a drag occurs, data must be associated with the drag which identifies what is being dragged. For example, when dragging the selected text within a textbox, the data associated with the drag is the text itself. Similarly, when dragging a link on a web page, the drag data is the URL of the link.
The drag data contains two pieces of information, the type, or format, or the data, and the data value. The format is a type string (such as text/plain for text data), and the value is a string of text. When the drag begins, you would add data by providing a type and the data. During the drag, in an event listener for the dragenter and dragover events, you would use the types of the data being dragged to check whether a drop is allowed. For instance, a drop target that accepts links would check for the link type text/uri-list. During a drop event, a listener would retrieve the data being dragged and insert it at the drop location.
Types are a MIME-type like string, such as text/plain or image/jpeg. You can also create your own types. The most commonly used types are listed at Drag Types.
A drag may provide data of several different types. This allows data to be provided in more specific types, often custom types, yet still provide fallback data for drop targets that do not support more specific types. It is usually always the case that the least specific type will be normal text data using the type text/plain. This data will be a simple textual representation.
e.dataTransfer.setData("application/x-bookmark", bookmarkString);
e.dataTransfer.setData("text/uri-list", "http://www.example.com");
e.dataTransfer.setData("text/plain", "http://www.example.com");
Here, data is added in three different types. The first type 'application/x-bookmark' is a custom type. Other applications won't support this type, but you can use a custom type for drags between areas of the same site or application. By providing data in other types as well, we can also support drags to other applications in less specific forms. The 'application/x-bookmark' type can provide data with more details for use within the application whereas the other types can include just a single URL or text version.
Note that both the text/uri-list and text/plain contain the same data in this example. This will often be true, but doesn't need to be the case.
If you attempt to add data twice with the same format, the new data will replace the old data, but in the same position within the list of types as the old data.
You can clear the data using the clearData method, which takes one argument, the type of the data to remove.
e.dataTransfer.clearData("text/url-list");
When dragging, there are several operations that may be performed. The copy operation is used to indicate that the data being dragged will be copied from its present location to the drop location. The move operation is used to indicate that the data being dragged will be moved, and the link operation is used to indicate that some form of relationship or connection will be created between the source and drop locations.
You can specify which of the three operations are allowed for a drag source, by setting the effectAllowed property within a dragstart event listener.
e.dataTransfer.effectAllowed = "copy";
The effects are:
none |
no operation is permitted |
copy |
copy only |
move |
move only |
link |
link only |
copyMove |
copy or move only |
copyLink |
copy or link only |
linkMove |
link or move only |
all |
copy, move, or link |
Note that these values must be used exactly as listed above. If you don't change the effectAllowed property, then any operation is allowed, just like with the 'all' value. So you don't need to adjust this property unless you want to exclude specific types.
During a drag operation, a listener for the dragenter or dragover events can check the effectAllowed property to see which operations are permitted. A related property, dropEffect, should be set within one of these events to specify which single operation should be performed. Valid values for the dropEffect are none, copy, move or link. The combination values are not used for this property.
With the dragenter and dragover event, the dropEffect property is initialized to the effect that the user is requesting. The user can modify the desired effect by pressing modifier keys. Although the exact keys used vary by platform, typically the Shift and Control keys would be used to switch between copying, moving and linking. The mouse pointer will change to indicate which operation is desired, for instance, for a copy, the cursor might appear with a plus sign next to it.
You can modify both the effectAllowed and the dropEffect property during the dragenter or dragover events, if for example, a particular drop target only supports certain operations. Modifying the effectAllowed property lets you specify which set of operations are permitted at a certain drop target. For example, setting the effectAllowed property to copyMove allows a copy or move operation but prevents the user from performing a link operation.
You can modify the dropEffect property to override the user effect, and enforce a specific drop operation to occur. Note that this effect must be one listed within the effectAllowed property. Otherwise, it will be set to an alternate value that is allowed.
e.dataTransfer.effectAllowed = "copyMove";
e.dataTransfer.dropEffect = "copy";
It is most common to accept or reject a drop based on the type of drag data in the data transfer. For instance, allowing images or links or both. To do this, you can check the types of the dataTransfer object. The types are a list of the string types that were added when the drag began, in the order from most significant to least significant.
function doDragOver(e)
{
var plain = e.dataTransfer.types.contains("text/plain");
if (plain)
e.preventDefault();
}
In this example, we use the contains method to check if the type text/plain is present in the list of types. If it is, we will cancel the event so that a drop may be allowed. If the drag data does not contain a plain text, the event will not be cancelled and a drop cannot occur at that location.
LocalStorage
This is anotherimportant feature of HTML5 which will eliminate cookies now no longer websites will be storing cookies and sending them back in urls but instead they will save their data in localStorage which is a part of your browser memory it will also help for some websites to store some user information over there like for eg a background image for a google's home page which can be stored by google in the localstorage of its domain and no longer sending user information to server and retriving the image and doing stuff like that it will all be availble at client side and will help to send few requests to server and also decreasing the load on server and also helping internet to be faster.First to use it we have to check whether the browser supports it or not we can to this by writing a if loop
if(window.localStorage)
{
alert('your browser supports localstorage');
}
Now coming to its concept we can save website's data on client side using javascript like
localStorage.setItem('key_value',item_to_be stored);
var count = 10;
localStorage.setItem('count_recent',count);
Now that count value is stored in the localstorage database of the specific browser and if we want to retrieve that value next time instead of hitting the server what we can do is
var count_value = localStorage.getItem('count_value');
Thing to note here is that we are retrieving the value using key value of the data so it must be different for different data or it will be overridden
This can also help while rendring a page at client side we can store various information at client side so the call for a particular page be made depending on what client likes more like the types of adds that can be displayed.
We can also remove a particular item using
localStorage.removeItem('key_value');
Or clear the whole storage
localStorage.Clear();
SessionStorage
As name suggests it stores information for a particular seesion of a browser in a browsers sessionstorage place it performes same operation as localstorage but difference is that when we are using no of forms to be filed up page by page we can save the information in browsers storage rather than sending information to server again and again like for eg we are filling a 3 page form we will fill data of 1st page then send request to server for next page and also send that so that the 3rd page will be created based on the data of first two pages,yes we can do it using CGI script but now if we want to do it completely on client side then we will use javascript and sessionStorage now the question in your mind would be why sessionstorage and why not localstorage but the answer is suppose i made a 3 page form but when i script it using javascript i will be using same key value pair to save the data for eg for name i will be using name_value but this will give me an error if i will be opening that same page in 2 or more different instances of same browser as the value of that name_value will be overwritten and in the end the third page will be rendered wrongly on client side so for such purposes we use sessionStorage which will tempoprarly save value for different instance of a browser.And the syntax and checking is same as localStorage we simply have to replace local with session
Sqlite
To make a website online is one of the important features of HTML5 so the main thing here is to store the data of website which could be more than 10-20Mbs at client side and this can't be done using localstorage as per now only in opera we can change the amount of storage space for a particular domain but for rest of the browsers the size of localstorage is fixed which is about 5Mb.so now to make website offline we can use the Sqlite.
The Web SQL Database API isn't actually part of the HTML5 specification but it is a separate specification which introduces a set of APIs to manipulate client-side databases using SQL.
I'm assuming you are a great web developer and if that is the case then no doubt, you would be well aware of SQL and RDBMS concepts. If you still want to have a session with SQL then, you can go through our SQL Tutorial.
Web SQL Database will work in latest version of Safari, Chrome and Opera.
Here there are 3 methods by the use of which we can create a database and save data at client side.
-
openDatabase: This method creates the database object either using existing database or creating new one.
-
transaction: This method give us the ability to control a transaction and performing either commit or rollback based on the situation.
-
executeSql: This method is used to execute actual SQL query.
OPENDATABASE
The openDatabase method takes care of opening a database if it already exists, this method will create it if it already does not exist.
To create and open a database, use the following code:
var db = openDatabase('the_name_of_database_to_be_created', '1.0(|
version_of_database)', 'Test DB(Text_description_for_database)',
2 * 1024 * 1024(Size(here its 2Mb)),callback(
The_method_here_will_be _called_if_the_database_is_created(
this argument is not mendatory)));
EXECUTING QUERIES:
One thing to note here is the queries are executed inside a transaction that means a rollback will occur if the query is not executed.Now creating table and executing insert queries is explained below
var db = openDatabase('employee', '2.0', 'company', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS data (emp id unique, name)');
tx.executeSql('INSERT INTO data (emp id, name) VALUES (32467, "micheal")');
tx.executeSql('INSERT INTO LOGS (emp id, name) VALUES (32468, "ricky")');
});
Performing read operation in sqlite
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM data', [], function (tx, results) {
var len = results.rows.length, i;
msg = "Found rows: " + len + ";
document.getElementById('div_id').innerHTML += msg;
for (i = 0; i < len; i++){
alert(results.rows.item(i).log );
}
}, null);
});
GOING OFFLINE
Now this is again a game changing feature.This will help us to browse in offline mode either a particular page or whole website or pages visited on that website that truely depends on the website owner.This will help us to connect to net for a while download all data then disconnect and modify the data offline on the go and then update information when again connected to internet or check our mails by connecting to net dowloading all new mails then checking it on the go or when net is down then too we will feel connected to net just awesome.Coming to point this will help us browse web offline this can be done using a manifest attribute in html tag eg:-
<html manifest="~/filename.appcache">
here the extension of the manifest file is not yet fixed but belived to be .appcache and not .manifest as that will complicate things in visual studio as it already uses that extension
Now here we have to make a .appcache file which specifies the content that should be downloaded so as to surf this page offline.
Your cache manifest file can be located anywhere on your web server, but it must be served with the content type text/cache-manifest. If you are running an Apache-based web server, you can probably just put an AddType directive in the .htaccess file at the root of your web directory and for IIS users you should add a MIME type for that specific project hosted on IIS.
OK, so every one of your HTML pages points to your cache manifest file, and your cache manifest file is being served with the proper Content-Type header. But what goes in the manifest file? This is where things get interesting.
The first line of every cache manifest file is this:
CACHE MANIFEST
After that, all manifest files are divided into three parts: the “explicit” section, the “fallback” section, and the “online whitelist” section. Each section has a header, on its own line. If the manifest file doesn’t have any section headers, all the listed resources are implicitly in the “explicit” section. Try not to dwell on the terminology, lest your head explode.
Here is a valid manifest file. It lists three resources: a CSS file, a JavaScript file, and a JPEG image.
CACHE MANIFEST
/filename.css
/filename.js
/picture.jpg
This cache manifest file has no section headers, so all the listed resources are in the “explicit” section by default. Resources in the “explicit” section will get downloaded and cached locally, and will be used in place of their online counterparts whenever you are disconnected from the network. Thus, upon loading this cache manifest file, your browser would download filename.css, filename.js, and picture.jpg from the root directory of your web server. Then you could unplug your network cable and refresh the page, and all of those resources would be available offline.
If your entire web application is contained in a single page, just make sure that page points to the cache manifest using the manifest attribute. When you navigate to an HTML page with a manifest attribute, the page itself is assumed to be part of the web application, so you don’t need to list it in the manifest file itself. However, if your web application spans multiple pages, you should list all of the HTML pages in the manifest file, otherwise the browser would not know that there are other HTML pages that need to be downloaded and cached.
NETWORK
Here is a slightly more complicated example. Suppose you want your application to know who visits, using a visit.cgi script that is loaded dynamically from an <img /> attribute. Caching this resource would defeat the purpose of tracking, so this resource should never be cached and never be available offline. Here is how you do that:
CACHE MANIFEST
NETWORK:
/visit.cgi
CACHE:
/filename.css
/filename.js
/picture.jpg
This cache manifest file includes section headers. The line marked NETWORK: is the beginning of the “online whitelist” section. Resources in this section are never cached and are not available offline. (Attempting to load them while offline will result in an error.) The line marked CACHE: is the beginning of the “explicit” section. The rest of the cache manifest file is the same as the previous example. Each of the three resources listed will be cached and available offline.
FALLBACK:
There is one more type of section in a cache manifest file: a fallback section. In a fallback section, you can define substitutions for online resources that, for whatever reason, can’t be cached or weren’t cached successfully. The HTML5 specification offers this clever example of using a fallback section:
CACHE MANIFEST
FALLBACK:
/ /offline.html
NETWORK:*
First, consider a site that contains millions of pages, like Wikipedia. You couldn’t possibly download the entire site, nor would you want to. But suppose you could make part of it available offline. But how would you decide which pages to cache? How about this: every page you ever look at on a hypothetical offline-enabled Wikipedia would be downloaded and cached. That would include every encyclopedia entry that you ever visited, every talk page (where you can have makeshift discussions about a particular encyclopedia entry), and every edit page (which you can actually make changes to the particular entry).
That’s what this cache manifest does. Suppose every HTML page on Wikipedia pointed to this cache manifest file. When you visit any page that points to a cache manifest, your browser says “hey, this page is part of an offline web application, is it one I know about?” If your browser hasn’t ever downloaded this particular cache manifest file, it will set up a new offline “appcache” (short for “application cache”), download all the resources listed in the cache manifest, and then add the current page to the appcache. If your browser does know about this cache manifest, it will simply add the current page to the existing appcache. Either way, the page you just visited ends up in the appcache. This is important. It means that you can have an offline web application that “lazily” adds pages as you visit them. You don’t need to list every single one of your HTML pages in your cache manifest.
Now look at the fallback section. The fallback section in this cache manifest only has a single line. The first part of the line (before the space) is not a URL. It’s really a URL pattern. The single character (/) will match any page on your site, not just the home page. When you try to visit a page while you’re offline, your browser will look for it in the appcache. If your browser finds the page in the appcache (because you visited it while online, and the page was implicitly added to the appcache at that time), then your browser will display the cached copy of the page. If your browser doesn’t find the page in the appcache, instead of displaying an error message, it will display the page /offline.html, as specified in the second half of that line in the fallback section.
-
Now the star in NETWORK says that anything that isn’t in the appcache can still be downloaded from the original web address, as long as you have an internet connection.It’s called the “online whitelist wildcard flag.
-
All this things mentioned in the manifest file ae saved in Application Cache area of the browser you can see this in any browser using its developer tools
-
Till here we saw what is a appcache file and what all things it contains now we will see what are the events that are fired for this manifest file
-
Following are the events of Application cache:-
-
checking - The browser is checking for an update, or is attempting to download the cache manifest for the first time. This is always the first event in the sequence.
-
noupdate - The cache manifest hadn't changed.
-
downloading - The browser has started to download the cache manifest, either for the first time or because changes have been detected.
-
progress - The browser had downloaded and cached an asset. This is fired once for every file that is downloaded (including the current page which is cached implicitly).
-
cached - The resources listed in the manifest have been fully downloaded, and the application is now cached locally.
-
updateready - The resources listed in the manifest have been newly redownloaded, and the script can use swapCache() to switch to the new cache.
-
obsolete - The cache manifest file could not be found, indicating that the cache is no longer needed. The application cache is being deleted.
-
error - An error occurred at some point - this could be caused by a number of things. This will always be the last event in the sequence.
You can use this events to see if the data has properly stored or not as even if there is a error to fetch one ile whole process fails
var app = window.applicationCache;
switch (app.status) {
case app.UNCACHED: return 'UNCACHED';
break;
case app.IDLE: return 'IDLE';
break;
case app.CHECKING: return 'CHECKING';
break;
case app.DOWNLOADING: return 'DOWNLOADING';
break;
case app.UPDATEREADY: return 'UPDATEREADY';
break;
case app.OBSOLETE: return 'OBSOLETE';
break;
default:
return 'UKNOWN CACHE STATUS';
break;
};
Also the files from manifest files are not fetcched if the manifest file doesnt change for eg script.js file of filename.appcahce is changed but since filename.appcache is not changed the newly written script.js will not be downloaded so it is a good practice to include version in comments like
CACHE MANIFEST
#hash is used to show that this line is a comment
#Version 1.0
To programmatically update the cache, first call applicationCache.update(). This will attempt to update the user's cache (which requires the manifest file to have changed). Finally, when the applicationCache.status is in its UPDATEREADY state, calling applicationCache.swapCache() will swap the old cache for the new one.
var app = window.applicationCache;
app.update();
...
if (app.status == window.applicationCache.UPDATEREADY) {
app.swapCache(); }
Note: Using update() and swapCache() like this does not serve the updated resources to users. This flow simply tells the browser to check for a new manifest, download the updated content it specifies, and repopulate the app cache. Thus, it takes two page reloads to server new content to users, one to pull down a new app cache, and another to refresh the page content.
The good news: you can avoid this double reload headache. To update users to the newest version of your site, set a listener to monitor the updateready event on page load:
window.addEventListener('load', function(e) {
window.applicationCache.addEventListener('updateready', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?')) {
window.location.reload();
}
} else {
}
}, false);
}, false);
You can also use eventhandlers on window.applicationCache like:-
window.applicationCache.addEventListener('cached', handleCacheEvent, false);
Web Workers
Web Workers are basically a API specification that lets you create background JavaScript threads to process CPU intensive tasks. Normally in browsers a single thread is created to handle all the JavaScript code. So whatever JavaScript code in the browser is executed in that single thread; whether you are doing some calculation or updating page elements. The downside of this is that some CPU intensive piece of JavaScript can render the page unresponsive or slow it to a crawl.
Web Workers alleviate this problem by letting you create multiple JavaScript threads that will run independent of each other, this will prevent one CPU intensive piece of JavaScript from interfering with the UI code.
Before you create any Web Worker related code you will need to find if your browser supports HTML5 Web Workers. Failure to do this will send your Web Workers to slog in Never Never Land. The following code will allow you to check if your browser supports Web Workers.
CHECK WEB WORKER SUPPORT:
function getWebWorkerSupport() {
return (typeof(Worker) !== "undefined") ? true:false;
}
CREATE A WEB WORKER:
Once we have checked that Workers are supported in the browser we are ready to put them to task. In this example we will create a simple Web Worker that will ‘Add’ or ‘Substarct’ two numbers. The example is deliberately kept simple to keep the discussion focused on Worker details; in reality you would not use Workers for such simple things, but for more elaborate and CPU intensive tasks. Below is a small piece of JavaScript code that does the actual arithmetic calculation. This our Worker. It is stored in the ‘Maths.js’ file.
function addNumbers(x,y) {
return x + y;
}
function subNumbers(x,y) {
return x-y;
}
this.onmessage = function (event) {
var data = event.data;
switch(data.op) {
case 'sub':
postMessage(subNumbers(data.x, data.y));
break;
case 'add':
postMessage(addNumbers(data.x, data.y));
break;
default:
postMessage("Wrong operation specified");
}
};
Now that we have or Worker file ready we need to call it from our main file.
The following line will create a new Worker thread and run the code stored in ‘Maths.js’.
arithmeticWorker = new Worker("Maths.js");
Once we have created Workers we need to send and receive messages from them. For that we need to add a event handler to the main calling code.
arithmeticWorker.onmessage = function (event) {
document.getElementById("output").value = event.data;
};
Now whenever a Worker posts a message the ‘onmessage’ event is fired and the code within it is executed. The data passed by the Worker is stored in the event.data container. We have seen how to receive a message from the Worker but how to we post one. Posting a message to the Worker is very simple.
arithmeticWorker.postMessage('Main says...');
The message can be a simple variable or a JSON object. The same event management applies to the Worker file. Whenever the main page posts a message to the Worker the Worker can receive the message in a ‘onmessage’ event handler, at the same time the Worker can post a message to the main page with the ‘postMessage’ method.
postMessage('Worker says...');
Below is the main page
<!DOCTYPE html>
<body>
<input type="text" id="x" value="2" />
<br />
<input type="text" id="y" value="3" />
<br />
<input type="text" id="output" />
<br />
<input type="button" id="subtButton" value="Substract" />
<input type="button" id="addButton" value="Add" />
<script>
/* Check if Web Workers are supported */
function getWebWorkerSupport() {
return (typeof(Worker) !== "undefined") ? true:false;
}
if(getWebWorkerSupport() == true)
{
var x,y,message;
/* Create a new worker */
arithmeticWorker = new Worker("Maths.js");
/*
Add a event listener to the worker, this will
be called when the worker posts a message.
*/
arithmeticWorker.onmessage = function (event) {
document.getElementById("output").value = event.data;
};
/* Register events for buttons */
document.getElementById("subtButton").onclick = function() {
/* Get the values to do operation on */
x = parseFloat(document.getElementById("x").value);
y = parseFloat(document.getElementById("y").value);
message = {
};
arithmeticWorker.postMessage(message);
}
document.getElementById("addButton").onclick = function() {
/* Get the values to do operation on */
x = parseFloat(document.getElementById("x").value);
y = parseFloat(document.getElementById("y").value);
message = {
};
arithmeticWorker.postMessage(message);
}
}
</script>
</body>
</html>
TERMINATING WORKER
Once the main page starts a Worker thread, the thread doesn’t terminate by itself. The calling page has to explicitly ask the Worker to terminate. This may become necessary because creating each new Worker consumes precious browser resources, which you will need to reclaim once the Workers task is no longer required.
arithmeticWorker.terminate();
Background
All tags are not covered as there where many so you can find them on w3schools.com.Also took some help for webworkers.
Using the code
Please see readme file which is present in *.zip folder and also the database is limited to country India so please select INDIA as a country in html5.zip and the rest code is javascripted which is self explainatory or if any doubt please comment or mail i will explain it.