Learn HTML 5 step by step - Part 3

HTML 5 Media

Media is one of the important part in today’s internet world. Everywhere you can see either a video or an audio playing around somewhere on a webpage. Implementing such functionality was really a big pain earlier. We had to rely on Object tag which internally required some third party players like flash. When it comes to devices which don’t have support for flash we end up with nothing. Butnow HTML 5 mad it easy with its new standard video and audio tag.

Working with Video element

In this lab we will understand how to work with new video element in HTML5.

Step 1 – Prepare video

Download a sample video file from somewhere for the demo purpose. If you want you can download it from sample attached.

Step 2 – Create HTML page

Create a new HTML page called Media.html and put following contents inside it
<video controls width="500px" id="vid">
<source src="vid.mp4" />
</video>
You will notice a special attribute called “controls” in the video tag. Adding this attribute simply make control bar in the player visible. Control bar is simple strip normally seen in the bottom section and contain few buttons like “play”, “pause”, “stop” etc.
Note:
  • Please make sure that video and Html file is kept in same directory. In case you want both of them to be placed in different directory, in that case make sure to set the “src” attribute accordingly.
  • HTML 5 video element only supports mp4, webm, 3gpp, m4v, mpeg, ogg, quicktime, x-ms-wmvright now.
Output:
This is how you will get the output.
Lab 15: Scripting with Video element
In this lab we will try to access the video features like play / pause / Stop etc. using JavaScript.
Step 1: Create HTML Page
Create new html page called Media01.html or you can use the same html file used in previous lab. Provide the video source insrc attribute. This time we will not set 'controls' attribute as we will be doing that using JavaScript.


<video width="500px" id="vid">
<source src="vid.mp4" />
</video>

Step 2: Add 3 buttons on the same html page for play, stop, end & one input type range element for volume control.

Add the below elements
<input type="button" name="name" value="Play" id="BtnPlay" />
<input type="button" name="name" value="Stop" id="btnStop" />
<input type="button" name="name" value="End" id="btnEnd" />
<input type="range" name="name" value="0.1" min="0" max="1" step="0.1" id="slideVolume" />

Step 3: Create JavaScript functions for controlling the video. The below function will helps us to play and pause the video.

function PlayOrPause()
{
var v = document.getElementById('vid');
if (v.paused || v.ended)
{
  v.play();
  document.getElementById('BtnPlay').value = "Pause";
}
else
{
  v.pause();
  document.getElementById('BtnPlay').value = "Play";
}
}

Below function will stop the video at the 6th second as we set the currentTime to 6.
function Stop()
{
  var v = document.getElementById('vid');
  v.pause();
  v.currentTime = 6;
  document.getElementById('BtnPlay').value = "Play";
}

Below function will end the video and we set the currentTime to duration where duration is the total video time.
function End()
{
  var v = document.getElementById('vid');
  v.pause();
  v.currentTime = v.duration;
  document.getElementById('BtnPlay').value = "Play";
}

Below function will set the volume of video player to the range which is between 0 to 1.
function ChangeVolume(element)
{
  var v = document.getElementById('vid');
  v.volume = element.value;//For mute set it to 0
}

Output:

If you want to show some default image when the player is loaded on pagethen set an attribute called poster with imageurl.
<video controls width="500px" id="vid" poster="MyPoster.jpg">
<source src="vid.mp4" />
</video>

Audio element

Just like video, audio has beenan issue before HTML 5. We didn’t had any option other than relying on object tag and third party libraries. But now HTML 5 Audio element made it easy.
Html5 has provided audio element which can play audio. Lets try it.
Step 1: Prepare audio
Download a sample audio file from somewhere for the demo purpose. If you want, you can download it from sample attached.
Step 2:  Create HTML page
Create a new HTML page called Audio.html and put following contents inside it.
<audio id="audctrl" controls>
<source src="aud.mp3" type="audio/mp3" />
</audio>
Note:
  • Please make sure that audio and Html file is kept in same directory. In case you want both of them to be placed in different directory, in that case make sure to set the “src” attribute accordingly.
  • HTML 5 audio element only supports mp3, wav, ogg format right now.

Output:
Lab 17: Scripting with Audio element
In this lab we will try to access the Audio features like play / pause / Stop etc. using JavaScript.
Step 1: Create HTML Page
Create new html page called Auio01.html or you can use the same html file used in previous lab. Provide the audio source in src attribute. This time we will not set controlsattribute as we will be doing that using JavaScript.
<audio id="audctrl">
        <source src="aud.mp3" type="audio/mp3" />
</audio>

Step 2: Add 3 buttons on the same html page for play, stop, end & one input type range element for volume control.
Add the below html
<innput type="button" name="name" value="Play" id="BtnPlay" />
<input type="button" name="name" value="Stop" id="btnStop" />
<input type="button" name="name" value="End" id="btnEnd" />
<input type="range" name="name" value="0.1" min="0" max="1" step="0.1" id="slideVolume" />

Step 3: Create JavaScript functions for controlling the audio. The below function will help us to play and pause the audi

function PlayOrPause()
{
  var v = document.getElementById('audctrl');
  if (v.paused || v.ended)
  {
    v.play();
    document.getElementById('BtnPlay').value = "Pause";
   }
   else
   {
     v.pause();
     document.getElementById('BtnPlay').value = "Play";
   }
}

Below function will stop the audio at the 6th second as we set the currentTime to 6.
function Stop()
{
  var v = document.getElementById('audctrl');
  v.pause();
  v.currentTime = 6;
  document.getElementById('BtnPlay').value = "Play";
}

Below function will end the audio and we set the currentTime to duration where duration is the total audio time.
function End()
{
  var v = document.getElementById('audctrl');
  v.pause();
  v.currentTime = v.duration;
  document.getElementById('BtnPlay').value = "Play";
}

Below function will set the volume of audio player to the range which is between 0 to 1.
function ChangeVolume(element)
{
  varv = document.getElementById('audctrl');
  v.volume = element.value;//For mute set it to 0
}
Output:
Note: You will not see the audio player on the screen.

Drag and Drop Demo 1
Earlier, for implementing Drag and Drop functionality, developers were used to write their own custom logic. But HTML5 came up with its own Drag and Drop API which will make our life much more easily and more than that we will get to see standard code everywhere.
Let’s see how step by step we can practically implement Drag and Drop functionality.
Step 1: Prepare image
Download a sample image file from somewhere for the demo purpose. If you want, you can download it from sample attached.

Step 2: Let say you want to drag an image, set the draggable attribute to true for that<img/>
<img src="fish.png" style="width:179px;height:120px;top:200px;" draggable="true" id="img11" ondragstart="drag(event)" />
Output:
Step 3: What should happen when you drag?
So specify the ondragstart event and let’s call a function drag(event) where ‘event’ specifies what data to drag.
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
ev.dataTransfer.setData() method will set the datatype & value of dragged data. In our case it is an tag id.

Step 4: Where to drop this fish? In a bowl i.e. - a div
<div id="div1" class="bowl" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
Output:
Note: I have applied the style and set the background-image of div with this bowl image.
The ondragover event specifies where the dragged data to be dropped. This is needed because by default data or elements cannot be dropped on other elements. To allow drop, we must override the default behaviour of element. This could be done by calling ev.preventDefault() method.
function allowDrop(ev) {
ev.preventDefault();
}

Step 5: Now drop the element, ondrop event will get called automatically when you leave the mouse from dragged element. So on drop event, I called a drop() function.
function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
Explanation:
  • ev.preventDefault() method is called just to prevent default behaviour of handling data by browser.
  • Get the dragged data using the same type which we used while setting it. Method used is ev.dataTransfer.getData("text"). Append the dragged element i.e. - fish on the drop element i.e. - bowl
Output:
Select a fish with a mouse and drag it towards a bowl & drop it(leave the mouse). Isn’t it cool and simple ☻ ?

Drag and Drop Demo 2
Let’s try to create some fancy functionality using Drag and Drop feature of HTML5. I will be creating face puzzle wherein attaching the parts of face like nose, eyes, and lips, create a face.

Step 1: Create a HTML page
Create a HTML page with name DragDrop2.html and copy the below css (Cascading Style Sheet) & html code.

HTML & Css Code
<style>
        body {
            cursor: pointer;
            text-align: center;
        }
        .divdrag {
            position: relative;
            border: 0px solid rgba(0, 0, 0, .25);
            width: 300px;
            height: 300px;
            padding: 10px 10px10px10px;
            float: left;
        }
        .face {
            background-image: url('face.jpg');
            background-repeat: no-repeat;
            width: 424px;
            height: 510px;
            border: 1px dotted grey;
            padding: 0 0 0 0;
        }
.facetr td {
            text-align: center;
            border: 1px dotted #f7ecec;
        }
</style>
 <h2>Create the face</h2>
    <div class="divdrag">
    <img src="eye1.png" alt="eye" draggable="true" id="eye1" ondragstart="drag(event)" />
    <img src="eye2.png" alt="eye" draggable="true" id="eye2" ondragstart="drag(event)" />
    <img src="nose2.png" alt="nose" draggable="true" id="nose2" ondragstart="drag(event)" />
    <img src="eye4.png" alt="eye" draggable="true" id="eye4" ondragstart="drag(event)" />
    <img src="nose1.png" alt="nose" draggable="true" id="nose1" ondragstart="drag(event)" />
    <img src="eye3.png" alt="eye" draggable="true" id="eye3" ondragstart="drag(event)" />
    <img src="smile1.png" alt="smile" draggable="true" id="smile1" ondragstart="drag(event)" />
   <img src="smile3.png" alt="smile" draggable="true" id="smile2" ondragstart="drag(event)" />
    <img src="smile2.png" alt="smile" draggable="true" id="smile3" ondragstart="drag(event)" />
   </div>
   <div style="float:left;">
     <a href="DragnDrop.html" title="Click here to reset" style="text-decoration:none;">
     <img src="direction.png" width="125" height="100" onclick="" />
     </a>
   </div>
    <div id="div1" style="width:300px;height:300px;float:left;">
    <table class="face">
          <tr>
               <td colspan="2" style="width:100%;">&nbsp;</td>
           </tr>
            <tr>
                <td colspan="2" style="width:100%;">&nbsp;</td>
            </tr>
            <tr>
                <td id="eye" style="width:50%" ondrop="drop(event)" ondragover="allowDrop(event)"></td>
                <td id="eye" style="width:50%" ondrop="drop(event)" ondragover="allowDrop(event)"></td>
            </tr>
            <tr>
                <td id="nose" ondrop="drop(event)" ondragover="allowDrop(event)" colspan="2"></td>
            </tr>
            <tr>
                <td id="smile" ondrop="drop(event)" ondragover="allowDrop(event)" colspan="2"></td>
            </tr>
        </table>
    </div>

Output:

Explanation:
  • I took all the images part and dumped inside a div.
  • Each image is set with attribute draggable=true &ondragstart event is implemented which will call drag() function.
  • Take another div which is the face outline. This div contains a table which specifies where you can drop the parts (Note: I had set the background image of table).
  • On which ever, I want to allow dropping images, specify ondrop&ondragover event. And call drop(event) &allowDrop(event) respectively.
  • For Reset, I am calling the same page again to keep it simple as shown below
<a href="DragnDrop.html" title="Click here to reset" style="text-decoration:none;">
<img src="direction.png" width="125" height="100" onclick="" /></a>
That’s it, designing of HTML is done.

JavaScript Code:
function allowDrop(ev) {
ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.effectAllowed = 'copy';
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  if (data.indexOf(ev.target.id) == -1) {
    ev.dataTransfer.clearData();
  }
  else {
    ev.target.appendChild(document.getElementById(data));
  }
}
Explanation:
The code for JavaScript remains same as explained in fish and a bowl example.
  • If you notice, in a drag() function I have used a line
    ev.dataTransfer.effectAllowed = 'copy';
    This line actually returns the type of operation we are performing like copy. So if you observe your cursor while dragging you will find the browser’s copy icon near the cursor. The other possible values are none, link, move or linkmove.
  • In a drop() function, I have checked for data.indexOf(ev.target.id) == -1 which means if “id” stored in data is partly matching with dropping target i.e. - td’s id then allow to drop else removes data stored in dataTransfer object.
Output:

Geo-Location

What is Geo-location?
Geo-location API in HTML 5 lets you to share your location via website. Longitude & latitude can be captured from JavaScript, which in turn can be sent to server and locate it on google maps.

Where it is helpful?

As it can capture your accurate latitude, longitude, altitude, speed, timestamp. So for getting your location’s weather, traffic, or nearby spots, it will be very helpful.

What about privacy if it accesses my location?
The problem with geolocation API is, it could break the security if user is tracked directly from browser. Since it is about compromising user’s privacy, the position is not available unless user accepts it in the browser. User can remain in control as a popup occurs as shown below
This is specifically for internet browser. For other browser the popup may differ. It also specifies which website wants to track your physical location. You can decide whether to give access or not.
Note: This functionality works only in latest browsers like IE 9+, Chrome 5.0+, Firefox 3.5+ and mobile device with Android2.0+, IPhone3.0+
Let’s try out step by step and see how it works?
I want to know the latitude & longitude of place from where I am accessing my laptop. Let’s do a practical for this.
Initial Setup
Step1: Create a html page Geolocation.html.

Step2: I will try to see my position from where I am accessing my desktop in terms of latitude & longitude on a label on click of button, so take a label and a button on the page. Copy the JavaScript code below your html.
<input type="button" value="Get My Location" />
JavaScript Code
<script type=&rdquo;text/Javascript&rdquo;>
var x = document.getElementById("lblDisplay");

function getLocation() {
  document.getElementById("header").value = "Static Location";
   if (navigator.geolocation) {
    var opt = {
                    timeout: 6000,
                    maximumAge: 60000,
                    enableHighAccuracy: true
                };
    navigator.geolocation.getCurrentPosition(showPosition, errorCallBack, opt);
   } 
   else {
      alert('No support for geolocation');
   }
}
        
function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude +
            "Longitude: " + position.coords.longitude;
}

function errorCallBack(e) {
    switch (e)
    {
                case e.PERMISSION_DENIED:
       x.innerHTML = "User denied geolocation request";
                    break;
                case e.POSITION_UNAVAILABLE:
       x.innerHTML = "No position information available";
                    break;
                case e.TIMEOUT:
       x.innerHTML = "Timeout occured";
                    break;
                case e.UNKNOWN_ERROR:
        x.innerHTML = "Unknown error";
                    break;
      }
 }
</script>
Explanation:
  • I have created a function getLocation() which will find my current position.
    First of all this api is available using window.navigator.geolocation object.As we are asking for current position so it can get the current position from getCurrentPosition() method.
    This method accept first parameter as Position callback which is in our case showPosition() method. This method has an argument which is a position object. This argument allows you to retrieve the latitude and longitude of my location.
  • The second optional parameter ingetCurrentPosition() method is PositionError callback i.e. – errorCallBack(). This method has an argument which is a PositionError object. If you see above in code snippet, I have written a case to handle each type of error.
  • The third optional parameter to getCurrentPosition() method is PositionOption object. IT allows us to pass various options as explained some below.
    • timeout: When to retrieve a new value i.e.- after 1 sec (calculated in millisec).
    • enableHighAccuracy: When set to true specifies how accurate position should be retrieved. Definitely it will take bit long time for accurate retrieval.
    • maximumAge: How old a position is i.e.- 1 min (calculated in millisec). After which it will recalculate the location again.
Output:
Note:Better check the output in Internet Explorer 9+
How to update location automatically when location changes?
Initial Setup
Step1: Take a button & a label on the page.


<input type="button" value="Get My Location Updated" />

Step 2: Write a JavaScript function
varwatchid;
function getUpdatedLocation() {
  document.getElementById("header").value = "Dynamic Location";
  if (navigator.geolocation) {
    var opt = {
                timeout: 500,
                maximumAge: 1000,
                enableHighAccuracy: true
              };
   watchid = navigator.geolocation.watchPosition(showPosition, errorCallBack, opt);
  } 
  else {
                // no native support; maybe try a fallback?
  }
}
Explanation:
navigator.geolocation.watchPosition() : This method return the current position and keeps listening to geolocation and updating the position based on the timeout and maximumAge options being set as well as the users moves. It is similar to your GPS system.

How to stop getting updated location?
Initial Setup
Step1:Take another button on the page
<input type="button" value="Stop Updating Location" />

Step2: Write the below JavaScript function
function stopUpdatingLocation() {
   if (navigator.geolocation) {
   navigator.geolocation.clearWatch(watchid);
  }
}
Explanation:
navigator.geolocation.clearWatch() : This method will stop the watchPosition() method which takes a parameter watchid (watchid is the same variable which we have used with watchPosition() method).
Output:
 Geo location with Google Map
Now let’s try something innovative using whatever we have learnt till now.
I am going to use geolocation API to get the position and will use the co-ordinates to map it will google maps to get the direction of some place.
Initial Setup
Step 1: Create a html page with name Geolocation2.html

Step 2: Add reference to google map API JavaScript file in your html file.
<script src="http://maps.google.se/maps/api/js?sensor=false"></script>

Step 3:Add a div element to load the map.
 <div id="divmap" style="border:1px solid #ffd800;width:400px;height:400px;"></div>
Step 4: Add a button on click of which you will load the map& a textbox for entering the destination.
<input type="text" id="txtDestination" value="Delhi" />
<input type="button" value="Get Direction" />

Step 5: Copy the JavaScript code
JavaScript Code
<script type="text/javascript">

function GetMyDirection() {
      if (navigator.geolocation) {
       var opt = {
                    timeout: 500,
                    maximumAge: 1000,
                    enableHighAccuracy: true
                };
       navigator.geolocation.getCurrentPosition(showPosition, errorCallBack, opt);
      } 
      else {
          alert('No support for geolocation');            
      }
}

function showPosition(position) {
  showInMap(position.coords.latitude, position.coords.longitude);
}

function showInMap(lat, lang) {

  vardirectionsService = new google.maps.DirectionsService();
  vardirectionsRenderer = new google.maps.DirectionsRenderer();

  var route = {
                origin: new google.maps.LatLng(lat, lang),
                destination: document.getElementById('txtDestination').value, travelMode: google.maps.DirectionsTravelMode.DRIVING
   };

 varmapOptions = {
                zoom: 10,
                center: new google.maps.LatLng(50.8504500, 4.3487800),mapTypeId: google.maps.MapTypeId.ROADMAP
 };

  var map = new google.maps.Map(document.getElementById("divmap"), mapOptions);
  directionsRenderer.setMap(map);
  directionsRenderer.setPanel(document.getElementById("divDriveDirection"));
  directionsService.route(route, function (result, status) {
  if (status === google.maps.DirectionsStatus.OK) {
      directionsRenderer.setDirections(result);
  }
  });
}

function errorCallBack(e) {
            switch (e) {
                case e.PERMISSION_DENIED:
                x.innerHTML = "User denied geolocation request";
                    break;
                case e.POSITION_UNAVAILABLE:
                x.innerHTML = "No position information available";
                    break;
                case e.TIMEOUT:
                x.innerHTML = "Timeout occured";
                    break;
                case e.UNKNOWN_ERROR:
                 x.innerHTML = "Unknown error";
                    break;
            }
}
</script>
Output:
Explanation:
On callback method of navigator.geolocation.getCurrentPosition() i.e. – showPosition() We called another method which will help to longitude & latitude on google map.
  • Create an object of google map direction service.
vardirectionsService = new google.maps.DirectionsService();

  • Create an object of google direction renderer which will help to render the direction on google map.
vardirectionsRenderer = new google.maps.DirectionsRenderer();

  • Set some route options
var route = {
             origin: new google.maps.LatLng(lat, long),
             destination: document.getElementById('txtDestination').value;              
             travelMode: google.maps.DirectionsTravelMode.DRIVING
         };
origin – Origin is my location so setting google map’s LatLng() method
desitnation – Whatever entered in a tetbox e.g – delhi
travelMode – Specifies mode of travel

  • Set some mapOptions
varmapOptions = {
                zoom: 30,
                center: new google.maps.LatLng(20, 77),
                mapTypeId: google.maps.MapTypeId.ROADMAP
         };
zoom – Specifies the default zoom
center- Specifies where to center the map
maptypeId – As we have selected DRIVING, so show the roads as type

  • Finally create a map
var map = new google.maps.Map(document.getElementById("divmap"), mapOptions);
directionsRenderer.setMap(map);   
directionsService.route(route, function (result, status) {
      if (status === google.maps.DirectionsStatus.OK) {
           directionsRenderer.setDirections(result);
      }
});

  • Show all the details about the route and direction to reach the destination from origin using below line
directionsRenderer.setPanel(document.getElementById("divDriveDirection"));
That’s it now run your application and play with it.

Web Worker
What is Web Worker?
Before I take any further step, let me ask you a simple question. Have u ever end up with following error in your web application.
If yes then solution for this problem is Web Worker. (Appearance of error display may be different in different browser).
Long running JavaScript will make UI unresponsive and many times we may end up with above error. Only solution for such problem will be client side multi-threading. Unfortunately it was not possible earlier but now with HTML5, by using Web Worker we can implement multi-threading in client side world.
Let’s do a small demo to understand Web Worker

 Understanding web Worker - Simple
This will be a very simple lab. Here will accept a number “N” from end user and then display sum of first “N” numbers.
Note: We will start our demo without Web Worker, Understand the output and then migrate it to Web Worker.

Step 1 : Create new Asp.Net Project
Open Visual studio. Click File>>New Project.
From the dialog box select Web in left section “Asp.Net Web Application” in right section and click Ok.
Select Empty in the next dialog box and click ok.

Step 2: Create HTML file
Put following HTML in the bodyWebWorker.Html file.
<input type="text" name="myText" id="myText" value=" " />
<input type="button" name="name" value="Generate" />

Step 3: Download Loading image
Get a GIF image of your choice from somewhere and name it loading.gif and place it in the project. (If you want you can download it from sample attached.)

Step 4: Download jQuery
Download jQuery file from jQuery.com or download it from sample attached and include it in the project.
Just on a quick note, jQuery is a JavaScript library which will make DOM manipulation and DOM traversing easier. In simple words, using this library we can easily program against HTML.
This lab or series won’t expect participant to have knowledge on jQuery. We will be using only some of the feature of jQuery here which will be explained.

Step 5: Include jQuery
Simply include jQuery script file in the head section of WebWorker.html file as follows.
<script src="jquery-1.4.4.min.js"></script>

Step 6 : Write long running Script
Create JavaScript 'Generate' function as follows.
<script type="text/javascript">
function Generate()
{
     $('#divData').html("Generating");
     $('.MyLoading').show();
     var j = 0;

     for (i = 0; i<= parseInt($('#myText').val()); i++)
     {
        j = j+ i;
     }
     $('#divData').html("Result is " + j);
     $('.MyLoading').hide();
}
</script>
In 'Generate' function following things are done one after the other.
  1. Display “Generating..” text
  2. Display Loading Image
  3. Perform logical operation(long running operation – Add first N numbers)
  4. Display the result
  5. Hide loading image.
Note: In above code,
  • $('#divData') - will return element with id “divData”
  • html - function sets inner HTML of an element
  • show and hide – will show or hide the element.

Step 7: Press F5 and test the application.
(In your case you may have to put some big number to get error.)
You can notice two things in response.
  • Putting big number in textbox makes the page unresponsive.
    Reason for this is, every browser is internally defined with a fix interval for which it can execute script. When any script executes for more that defined interval such error is thrown.
  • We were expecting to get loading image when Generate button is clicked but unfortunately it won’t happen either. In current case, thread which is responsible for execution of long running script is also responsible for rendering of UI. As the thread is busy with execution of script, UI changes won’t get rendered hence image won’t get displayed unless execution of script completes.

Step 8: Start with Web Worker
Now in order to work with Web Worker, first we have to move long running code into a separate JavaScript file. So create a new JavaScript file called MyWebWorker.js and put following code inside it.
var j = 0;
onmessage = function (e)
{ 
};
In above code variable onmessage is a global variable given by Web Worker which will point to a function containing long running script

Step 9: Move long running code to Web Worker file
Now before we perform this step, we have to understand two limitations of Web Worker.
  1. Inside Web Worker code, we cannot have any references to DOM elements.
  2. Inside Web Worker code, we cannot use any third party library functionality like jQuery.
After considering above two limitations, Web Worker code will be rewritten as follows.
var j = 0;
onmessage = function (e) {
    for (i = 0; i<= e.data; i++) {
        j = j+i;

    }
  postMessage(j);
};
In the above code call to postMessage function send back final response to the caller. If you are confused, be relax and continue with lab and I will promise that at the end will be simple for you.

Step10: Invoke Web Worker
Open WebWorker.html file and change Generate function as follows.


function Generate()
{
    $('#divData').html("Generating");
    $('.MyLoading').show();
    var c = new Worker("MyWebWorker.js");
    c.onmessage = function (e)
    {
        $('#divData').html("Result is " + e.data);
        $('.MyLoading').hide();
    };
    c.postMessage(parseInt($('#myText').val()));
}
As you can see in the place we have created an instance of Worker which is a part of HTML 5 specification. It exposes two major things.
  • postMessage function, which is an indication to worker to start the work in another thread. It simply make a call to onMesssage function in Worker file.
  • onMessage property, which is simply a functional pointer given by web worker. It act as a callback function. It will get executed once worker thread completes its execution. In simple words, postMessage function in a worker file calls this method.
Step 11: Execute and Test
Press F5 and execute the application.

Let’s understand the complete code flow.


Web Worker with Web API

Web API is an Asp.Net technology for creating REST based services. You can learn more about it from here.
You may be wondering what’s so special about this lab.
You might have worked with REST services 100 times prior.
As you know Service is a server side concept whereas HTML & JavaScript are a client side concepts. To invoke server side functionality from client side we use AJAX. In market tons of third party libraries are available which will make Ajax calls easy for us. Libraries like jQuery, Angular etc.
So what’s the problem? Problem is, as I said before, Web Worker won’t allow use any third party library inside it. In simple words we cannot use jQuery or any other library functionality inside our MyWebWorker.js.

Let’s do a small lab and understand how to do it.
Step 1:  Download the Web API
Download the sample Web API project attached with this article.

Step 2: Execute the Web API
Open Web API project in visual studio, press F5 and execute it. Navigate to Api as shown in the figure.

(Different browsers may display Web API response in different style. In IE you may find a text file downloaded with Json data.)

Step 3:: Invoke Web API and return data
Create a new MyWebWorker.js to follows.
var j = 0;

onmessage = function (e) {

  var a = new XMLHttpRequest();
  a.onreadystatechange = function () {
    if (a.readyState == 4 &&a.status == 200) {
      postMessage(JSON.parse(a.responseText));
     }
  };
  a.open("get", "http://localhost:35871/api/WorkerTest", false);
  a.send();
};
As you can see, instead of using jQuery we have used pure XmlHttpRequest object to perform Ajax request.

Step 4: Change HTML page
Change HTML page content to following
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="jquery-1.4.4.min.js"></script>
<script type="text/javascript">
        function GetData() {
            $('#divData').html("Generating");
            $('.MyLoading').show();
            var c = new Worker("MyWebWorker.js");
            c.onmessage = function (e) {
                $('#divData').html("Result is " + e.data.CustomerName + "---" + e.data.Address);
                $('.MyLoading').hide();
            };
c.postMessage(parseInt($('#myText').val()));
        }
</script>
</head>
<body>
<input type="button" name="name" value="Generate" />
<span style="color: rgb(17, 17, 17); font-family: 'Segoe UI', Arial, sans-serif; font-size: 14px;"></body>
</html></span>

Step 5: Execute and Test
Press F5 and execute the application.

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 ...