101 Javascript performance improvement techniques




Variables and Declarations

1. Variables much better than array and objects

Javascript is untyped language but the performance improvement starts from declaring variables and accessing them. Variables and literal values faster than object properties and array items look ups.
Declaring variables and accessing them

var user_email = 'xxx@xx.com';

console.log(user_email); //xxx@xx.com

Declaring objects with properties

var user = {email: 'xxx@xx.com'};

console.log(user.email); //xxx@xx.com

2. let is faster than var in function scope

let is block scoped and var is block scoped. let clears the memory when it is not needed, var exists all over function scope, so let always faster than var when there are different blocks. let solves the closures problem too.
Declaring variables with var and let

for(var i=0;i<length;i++){...}
for(let i=0;i<length;i++){...}
            
jsperf

3. Make sure that there is no native method for the same job

The same job you can do using native method and in your way of implmentation. if you are going to implement the functionality, take time to find native method can do the work. Native methods can give you better performance.
Sample for using native methods

var arr = [];
arr.push(1);
arr.pop();
            

4. Combine the variable declarations

Declaring the variables can also be optimizable. All the declarations should be in one statements, this handle the memory allocation for all at one time.

var foo,
    blah,
    flag;
            

5. Assign value in creation time, updations costs more.

if you seperate creations and value assignment of variables that would be a bad design. Assign the default values at the time of creations.

var foo = "str",
    blah = 10,
    flag = false;
        

6. Literals executes faster than Objects.

Literal notation executes faster than object notation when declaring variables with datatype constructors.
Declaring a variable in literal notation

            var str = 'string';
            var obj = {a:1,b:2};
            
Declaring variables using datatype constructors

            var str = new String();
            var arr = new Array();
            

7. For toggling purpose use 0/1 instead of Boolean type.

Using 0/1 helps to increase the performance, the value numeric values always better than boolean datatype.

            var flag = 0;
            
            function toggleFlag(val){
                if(val){
                    val = 0;
                }else{
                    val = 1;
                }
                return val;
            }
            

8. Do not use concat for string concatenation, use '+'

For concatenation use "+" and the native method concat doesn't perform well, when considering the performance.

            var str = "this";
            str += "is";
            str += "awesome";
            

9. parseInt can be replaced with ~~(1,'12.5')

parseInt job can be done by the statement ~~(1,numericString) with better optimization.

                var numberStr = '12.5';
                parseInt(numberStr); // 12.5
                ~~(1,numberStr); //12.5
                

10. Compound assignment of let or const give bad results

This is the issue with compiler, the function containing let or const are not optimizable.

Arrays

11. Avoid multi-dimensional arrays

Array items lookup bit costly, in case of multi-dimentional arrays that delivers not good results. Multi-dimentional array look up goes through each dimension every item comparison.

            var maArr = [[1,2,3],[4,5,6],['a','b','c']];
            mArr[2][0] // returns 'a' 
            

12. Use array native methods for doing operations

As I discussed in early steps, I always recommend a native method in case of array manipulations, as most developers not aware of all methods. In case of array manipulations look ups and index handling are heavy operations, so better to go with native methods to perform the operations as much as possible.

13. For simple array findings use indexOf.

oh, yah! indexOf., you are about to find the existence of an item in simple array, user it. Finding the existence by looping through all the items in the array is bad for simple arrays.

            var simpleArr = [1,2,3,4];
            function find(arr, item){
                return arr.indexOf(item) !== -1; 
            }
            find(simpleArr,3); // returns true;
            

14. Use binary search for finding elements in array

Why binary search? in case of complex arrays binary search gives the difference compared to other techniques.

15. Arrays are faster than objects

Array look ups and index manipulations are faster than object properties manipulations, array manipulations deals with index but object properties needs lot of comparisons.

            var arr = [1,2,'c'];
            var obj = {foo:1,blah:2};
            arr[0];
            obj[blah];
            
jsPerf

16. Arrays with holes in it gives much impact on objective

Array should be well defined and need care in manipulations. Holes with in a array has the impact on performance and the manipulations needs high computations.

            var arr = [1,3];
            arr[4] = 'a';
            //wow you did it, you created an array with holes.
            

17. Array join faster than string concatenation

yes, it's true. Array join performs well in case of concatenating strings, thats proven by the performance benchmarks. its seems to be long way but it makes us to reach objective.

            var str1 = 'am';
            var str2 = 'awesome';
            var arr = [];
            arr.push(str1);
            arr.push(str2);
            arr.join(); // "am awesome"
            str1 + 'I' + str2; // "am I awesome"
            
            
jsPerf

18. Use splice(0,length) to clear the array

How do you clear an array, are you assigning new empty array to it, that's not good way. Array method splice can work better in this case.

            var arr = [1,2,3];
            arr.splice(0,arr.length); // arr => []
            
            
jsPerf

19. Typed Arrays are faster than native arrays

Typed arrays performs lot better than normal javascript array becuase typed array views are like single type arrays.

             var s_tyarrayUint8 = new Uint8Array(256 * 256 * 4);
            var s_tyarrayUint32 = new Uint32Array(256 * 256);
            
jsPerf MDN

20. Array.forEach wont give you much better results

The array native looping method forEach needs functions executions for each item in the array, so its always a bad choice for iterating through all the items in array. Use for loop as an alternative for it.
Iterating aray items with forEach

            var arr = [1,2,3,4];
            arr.forEach(function(){// doing something});
            
Iterating using for

            var arr = [1,2,3,4];
            
            for(var i=0;i<arr.length;i++){
                //some code
            }
            

Objects

21. >Construct objects instead of array when u need to do more find operations

when you need more find operations for set of items, constructing object will help you and performs well.

            var users = {axorg :{id:'axorg', name:'George'},
            byorg:{id:'byorg', name:'John'}};
            users['byorg']; // easiest way to find user object using id
            

22. Use Object.keys() to get list of keys in object

To get list of keys use the native method Object.keys() because looping through all object properties costs more computations.

            var obj = {a:1,b:2};
            Object.keys(obj); // return ['a','b']
            

23. Use property check instead of hasOwnProperty

Though hasOwnProperty its own significance, doing property check give you advantage over hasOwnProperty.

            var task = [{name:"do1",selected:true},{name:"do2"}];
            var selectedTasks = 0;
            for(var i=0;i<task.length;i++){
                if(task[i].selected){
                    selectedTasks++;
                }
            }
            

24. Avoid Object.create() instead use new

Object.create() have many advantages over new still its not good to go with it, performance petrices revealed that.

             function myClass(){
                //class definition
             }
             var klass = new myClass;
            
jsPerf

25. Make it undefined instead of using delete to clear the properties from object

delete leads to object manipulation, but making a property undefined wont cause for object recustruction.

            var obj = {prop1:1,prop2:2};
            delete obj.prop1; // don't do it.
            obj.prop1 = undefined; // its better
            

26. Object.defineProperty() costs more than direct property assignment

Object.defineProperty() it has so many features for controlling the property behaviour that makes the performance down, unless it is a public property don't define properties using Object.defineProperty()

            var obj = {};
            obj.prop1 = 1;
            obj.prop2 = 2;
            Object.defineProperty(obj,'prop3',{value:4});
            

Statements and Expressions

27. Do not use with statement.

A well known proverb "do not use with", we can consider as one of the dangarous things in javascript. By using it you won't get much benfit but you will be in danger in case of missing properties in passed object. It updates global variabels if there are no properties in passed object.
updating the object using with

            with (myObj) {
    foo = true;
    blah = true;
}
            
doing the same thing

            var objCopy = myObj;
            objCopy.foo = true;
            objCopy.blah = true;
            

28. Do not use eval

Here comes the evil of the javascript. eval opens a hole to support attackers. its executes the code slowly.

            eval("alert('hahahaha')"); //see the evil laugh
            

29. Clear the timers, once the your tasks are finished

clearInterval help you to clear the interval in javascript. what happens to the uncleared intervals, they runs forever.

            var interval, count = 0;
            interval = setInterval(function(){
            if(count == 1000) clearInterval(interval);
            count++;},100);
            

30. Avoid animations with JavaScript

Do not play with javascript variables, even though we have powerful engines making our main thread busy leads to unresponsive dialog or huge amount of memory occupation.

31. Do not hit userAgent maximum space allocated for localStorage/sessionStorage

If the localStorage space reaching to the limit set by user agent and you are still trying to make operations on localStorage it always goes slow.
//pushing records to localStorage

            for(var i;i<10000 code="" generaterecords="" guid="" i="" localstorage.setitem="">

32. Limit number of requests to localStorage

Number requests to persistent storage space proportionally equals to performance impact.

33. Comments need space

Though comments dont have much impact on performance but comments increases the files size that leads to increase load time, so its better to remove comments in production.

34. Make use of threading in Javascript

Do the heavy operations in separate thread, Web Workers help you to implement this in Javascript. WebWorkers creates seperate threads in javascript.

            var myThread = new WebWorker(url);
            myThread.onmessage = function(){
                //receives msgs 
            };
            myThread.postMessage(msg);
            

35. Use minimum number of web workers

There is a limit to number of webworker instances for same origin.

            

36. Do not Send and Receive large amounts of data.

Sending or Recieving data objects creates copies of the objects, in case of large amounts of data passing threads needs more momery allocations that would slowdown execution.

            

37. Websockets can give boost to your application

Implementing websockets let you get rid of http overhead, this technique can make you to build responsive realtime web applicatios.

            

38. Use requestAnimationFrame for better performance in using intervals.

If you are going to large operations on client-side like animations, iterating in frequent intervals, requestAnimationFrame helps to give smooth presentation without blocking the thread.

reqAF = window.requestAnimationFrame;

  var degrees = 0;
  function updateSel(timestamp) {
    document.querySelector('#foo').style.webkitTransform = "rotate(" + degrees + "deg)";
    console.log('updated to degrees ' + degrees);
    degrees = degrees + 1;
    reqAF(updateSel);
  }
  reqAF(updateel);
            

39. Give the preference to native in case of base64 encoding or decoding atab and btoa.

The best native and performant way for encoding and decoding data to and from base64. atab will give you the actual data from base64 encoded data. btoa. gives you base64 encoded data of the passed data./p>

            var str = ""RK_Awesome";
            var bStr = btoa(str);//returns base64 data
            var aStr = atob(bStr);//returns actual data
            
jsPerf

Regular Expressions

40. test is faster than exec when using regular expressions

Usually we will go with test to verify the regExp but exec always performs better than text.

            var str = "hello world!";
var result = /^hello/.test(str);
console.log(result); // true
var result = /^hello/.exec(str);
console.log(result); //returns matches array

            
jsPerf

41. search is faster then match

Here we have two string methods takes regular expression and finds the in the content search and match, which can be comparable, but the search wins.

            var str = "hello world!";
            var re = /^hello/;
var result = str.search(re);
console.log(result); // index of first match or -1
var result = str.match(re);
console.log(result); //returns matches array or null
            
jsPerf

42. replace works well compared to split and join.

Another string method performs better than a well used technique. Prefer to use replace for replacing a string in other string.

            var str = "Hello world";  
            str.replace("Hello", "Google");// good to go
            str.split("Hello").join("Google");// bad practice
            
            
jsPerf

Control statements

43. Avoid else-if, use switch instead.

44. Use !! if you are checking non-Boolean values.

45. Strict comparison slower than value comparison.

46. if-else faster than ternary. jsperf

47. Do not exceed your switch cases more than 128.

48. typeof is much faster than instanceOf. jsperf

49. Give first preference to boolean conditions when you are checking multiple conditions.

50. Write fail proof code and avoid try/catch.

51. try/final also gives same impact like try/catch put them in a function and call them to use

Loops


52. Avoid for-in loops.

53. Avoid for-of loops.

54. Mix conditions with control variables when using loops.

55. Use decrements instead of increment if possible.

56. Use break and continue.

57. Long Running Scripts.

Functions


58. Use closures.

59. Apply closure instead of bind.

60. Use call or apply or bind when binding or calling the functions to avoid correct this.

61. Use call instead of apply.

62. Create instance instead of creating object.

63. Creating instance with new better than calling a function. jsperf

64. Return direct value not the reference.

65. Do not create anonymous functions.

66. Pass less arguments to the function.

67. passing objects, arrays, dates are better than strings, boolean values

68. Prototype methods significantly faster then class methods.

69. Function expression slower than function declaration. jsperf

70. Never return arguments array or reference of it. it causes for memory leak. copy the arguments to a new array and return if you want to return.

71. Don't try to manipulate arguments object or create a variable with arguments name.

72. Returning a value always faster than implementing callback.

73. Don't touch __proto__ in your function declaration.

74. get and set declarations makes the functions unoptimizable.

75. Functions have debugger statement never think about performance.

76. Avoid recursions.

77. Native promises faster than callbacks. jsperf

DOM


78. Do not use global object directly, use references to those objects when you are doing multiple operation using the same object.

79. Use arrays instead of HTML Collection objects.

80. Avoid DOM Manipulation.

81. Do not change styles directly, deal with classes instead.

82. ClassName give better results than ClassList. jsperf

83. Batch your DOM changes.

84. Less DOM gives you much better performance.

85. Separate the DOM creation and adding.

86. Prefer to load DOM on demand.

87. Load the scripts after DOM load.

88. Compare nodes not the attributes

89. Better to use document.querySelector instead of Element.querySelector.

90. Data attribute selectors are slower than CSS selectors.

91. Attributes faster than data-* attributes.

92. Be careful with these things, you may lead to browser favorite dialog. Too much DOM interaction.

Event handling


93. Be care full with event bindings.

94. Take extreme care on events fires in less times.

95. Turn off the events when you are done.

96. Lock the events with in the scope.

97. Mouse-up event instead of click event.

Transportation and Delivering


98. Load dependencies on demand.

99. Minify your code for production.

100. Follow AMD pattern for best practices.

101. Use Caching more.

102. Use CDNs to load scripts fast.

Web Audio API


Introduction:



           Audio on the web was never thought of without a flash or a plugin in the formative years. An excellent audio element of HTML 5 “The Web Audio API” has brought in a great revolution without the help of the above mentioned elements and is capable of supporting sophisticated games and interactive applications.

Web Audio API

             The Web Audio API is basically a high-level JavaScript API that processes and integrated audio in web apps.

       The two different types: In general there are two audio API’s one being the Audio data API and the other is the Web Audio API .The creation, the processing and the controlling of audio within the webapps is much simpler in Web Audio API when compared to the low-level access of the audio data by the Audio Data API.

        Amazing Feature: The attractive feature if that it does not require a helper application such as plug-in or flash. The main purpose of this API is to include the capabilities that are found in modern game audio engines and the excellent tasks such as mixing ,  processing and filtering tasks that are found in modern desktop audio production application.

The Working:

      The AudioContext instance: This is one of the most powerful instance used for managing and playing all the sounds. Initially an audio context has to be created which is like a container. Inside the context one can create sources and then connect them to the nodes and finally connected to the destination in the form a chain.


     var context = new AudioContext() ;
     //Audio Container created.


Since WebAudioAPI is a based on webkit technology and is supposed to be supported on IOS6,’webkit’ should be appended to the audio context.


var context = new WebKitAudioContext();


Once the audio context container is created a source node can also be created. A source node can be an Oscillator which generates sound from scratch or audio files such as wav, mp3 can be loaded and played back.

To create an oscillator


Oscillator = context.createOscillator();


Then the oscillator is supposed to be connected to the destination which can be speakers.


Oscillator.connect(context.destination);


To generate sound instantly


Oscillator.noteOn(0);


Now once the audio context is created between the source and the destination there is another interface called the audionode. They act as intermediate modules used for processing.

There are several audio nodes such as the-

1. Gainnode: This is used for volume which can be created in the following way-


volumeNode = context.createGainNode();


One can set the volume using


volumeNode.gain.value = 0.3;


Now this can be connected to the source


Oscillator.connect(volumeNode);


2. The Biquad filter: To add complex effects to your sound forms a biquad filter is used. It is low-order filter.

3. The delay node: It delays the incoming node signal.

4. The audiobuffer node: It consists of an in-memory audio data stored in an audio buffer.

5. Panner node: It describes its position with right –hand Cartesian co-ordinates and positions an incoming audio stream in 3D space.

6. Convolver node: Given an impulse response it applies a linear convolution effect.

7. Dynamic Compressor Node: When multiple sounds are played together, it helps to prevent distortion by lowering the volume of the loudest part of the signal.

8. Wave Shaper node: Inspite of the distortion effect, it applies a curve distorter to add a soothing feeling to the signal. It is a non-linear distorter.

By combining the above mentioned code one can find a working demo.

Exploring the WEB AUDIO API:


The AudioPara: It is like the AudioNode. It can be set to a specific value or a different value.

Ended: It is an event that can be called when the media has reached the end of the play.

The media elements:


MediaElementAudioSource Node: It is an audio node consisting of <audio> and <video> element of the HTML 5.

MediaStreamAudioSource Node: It is an audio node that acts as an audio source consisting of webcam or microphone.

MediaStreamAudioDestination Node: It is an audio node consisting of the audio destination node.

   How to extract time and frequency?

Then check out the Analyser node.
Assume that Source ‘S’ is connected to Destination ‘D’


var analyser = context.createAnalyser();
S.connect(analyser);
analyser.connect(D);
var freqDomain = new Float32Array(analyser.frequencyinCount);
analyser.getFloatFrequencyData(freqDomain);


A channel Splitter and a Merger?
A channel splitter separated different channels of an audio source into a set of mono outputs. It is created using a method called createChannelSplitter

A channel merger unites the mono inputs into a single output. It is created using a method called createChannelMerger

AudioListener: It gives the position and orientation of a person listening to the audio.

In c# it is created in the following way:


AudioListener listener = new AudioListener();


Script Process Node: This helps in the generation, processing or analysing of audio used in JavaScript.

Audio Process (event): When a script process node is ready to be processed the event is fired.

AudioProcessing Event: When the script processor node Input Buffer is ready to be processed, the event is fired.

Offline Audio Context: It does not render the audio but generates it as fast as it can in the buffer.

Complete: When the Offline Audio Context is terminated it is fired.

Offline Audio Completion Event: The complete event implements the interface.

Share your screen over Web(Screen sharing with HTML5)

A whole new concept on how a user can share his desktop or browser screens to other users is Screen sharing .
Is it possible?

While webRTC has not yet been supported by IE and Safari and these browsers  donot support screensharing  as well,there are several webapps that allow you and me to share the screens without the need of any plug-ins.The only one thing that is required to allow screen sharing is a browser called Chrome.Some of the webapps that support this screen sharing is same.io,talky.io and appear.in

Want to know how to do this in chrome?

Then follow the below steps-
  1.          Type chrome://flags in the address bar
  2.          You will find a setting like  “Enable screen capture support in getUserMedia()”
  3.          Click the enable button
  4.          Restart your browser.


Webapps like same.io and talky.io allows a user to share their screens. By allowing your chrome browser to access your web camera and microphone and by clicking on the “Share my Screen” button the user can share his screens.

Once the user hits that button the user will be provided with a unique web url and if anyone gets to know this url can access your screen through the chrome browser.

The other webapp talky.io allows private sessions wherein a user can protect his screens using a password.

Appear.in is a web app for video meetings that allows the user to share the desktop screen to other participants.




However a tech savvy guy named Rafael Weinstein has proposed a technique which uses Mutation observers and a websocket.

Let’s see how this works:

  1. The presenter shares his screen to the viewer using a websocket
  2. As the user performs any scroll operation the observer sends the changes and the report back to the viewer using Rafael mutation summary library.

Another method on how screensharing is done is:
  1. Rewrite all the pages on the URL to absolute to prevent static images and CSS elements from broken links
  2. Clone the page’s document
  3. Make the clone readonly, hidden and non-selectable and prevent scrolling.
  4. Capture the current position of the screen and add them as data-* attributes as duplicate
  5. Create a new BLOB page as duplicate.


The code for this is as follows-

 function screenshot(){
    urlsToAbsolute(document.images);  
    urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']"));
    urlsToAbsolute(document.scripts);

    var screen= document.documentElement.cloneNode(true);

    screen.style.pointerEvents = 'none';
    screen.style.overflow = 'hidden';
    screen.style.userSelect = 'none';

    var blob1 = new Blob([screen.outerHTML], {type: 'text/html'});

    window.open(window.URL.createObjectURL(blob1));
 }

   

Before the final BLOB is created this java script code should be written so that  when then presenter scrolls the page the user follows.

Set the scrollX and scrollY positions


 addOnPageLoad().
 screen.dataset.scrollX = window.scrollX;
 screen.dataset.scrollY = window.scrollY;


and finally write this below code –


 var script = document.createElement('script');
 script.textContent = '(' + addOnPageLoad_.toString() + ')();';.
 screenshot.querySelector('body').appendChild(script);
 function addOnPageLoad() {
    window.addEventListener('DOMContentLoaded', function(e) {
        var scrollX = document.documentElement.dataset.scrollX || 0;
        var scrollY = document.documentElement.dataset.scrollY || 0;
        window.scrollTo(scrollX, scrollY);
    });
 }


Another method is make the screenshot as a png file and share it using a websocket.

 var img_mimetype = 'images/jpeg';
 var IMG_QUALITY = 90;
 var SEND_INTERVAL = 280;
 var wes = new WebSocket('ws://...', 'sample-protocol');
 wes.binaryType = 'blob';
 function captureAndSendTab() {
    var opts = {format: img_mimetype, quality: IMG_QUALITY};
    chrome.tabs.captureVisibleTab(null, opts, function(dataUrl){
       wes.send(convertDataURIToBlob(dataUrl, IMG_MIMETYPE));
    });
  }
 var intervalId = setInterval(function() {
     if (ws.bufferedAmount == 0) {
         captureAndSendTab();
      }
    }, SEND_INTERVAL);


Conclusion:


Though without the use of WebRTC we have several technologies that help us to make screen sharing possible we still have to wait for the WebRTC to take a leap in making this screen sharing possible with HTML5 .

So guys wait to see the revolution that WebRTC is going to bring.

Observe javascript variable changes

Introduction:


The most awaited recently launched chrome 36 browser has a unique feature called Object.Observe().If it is questioned like what is so unique about Object.Observe() then the answer would be given appropriately by a JavaScript developer.While developing websites or apps generally the code and the display is generally separated that is their structures are separated and when they are combined together and made to execute the display on the browser would not be as it is coded.With the help of JavaScript the user would get a WYSIWG (What you see is what you get) display based on exactly what the app is doing.Although Object.Observe() is a low-level API it solves several problems.

Observe javascript variable changes


What is object.observe() all about?

Object.observe() is nothing but a low-level primitive and an enabling technology that makes some JavaScript libraries and frameworks work faster and robust.It simplifies the problem by acting as a pipeline between the app’s datastructure and display.

One can simply state that Object.Observe() is simply a function that can simply be built into JavaScript though developers will not work on it directly but frameworks like backbone,Angular and Ember will add new libraries that will rely on Object.observe that will make the code and display in a proper sync.

Object.Observe() mainly follows a concept called as databinding which makes sure that the programs underlying code and the display are in a sync.

What is databinding all about?

As we know that while devolping an application a developer makes use of a MVC architecture.If a ser wants to declare a relationship between the data and the document object model and if a user wants to keep the document object model up to date a databinding is used.Databinding is mainly useful when we have a complex user-interface wherein we need to establish relationships between multiple elements in the views and the underlying data.

Example:
Let’s create a sample object.

     var mysample = { 
             label: 'hello', 
             completed: false 
          }; 
Whenever changes are made to the object a call back is issued.


     function observing(changes){ 
         changes.forEach(function(change, i){ 
         console.log('what property  has changed? ' + change.name); 
         console.log('how did it the property change? ' + change.type); 
   console.log('whats the current value of the object? ' + change.object[change.name]); 
        console.log(change); // all changes 
        }); 
    } 


When ever the call back function is used there is a change in the object multiple times so the changed values and the given values need not be the same thing.

We can then observe these changes using O.o(), passing in the object as our first argument and the callback as our second:


       Object.observe(mysample, observing); 

Some changes to the model can be as follows

      mysample.label = 'I love databinding’; 

We can change another property like this

      mysample.completeBy = '30/09/2014'; 

After some time if a user decides to delete the property completed from the object this can be done as follows-

     delete mysample.completed; 


Now it is easy for a user to identify how to delete an object and how to add a new object.

     Object.unobserve();
Once this method is uses any changes made to the object will no longer result in a list of change records.

     Object.unobserve(mysample,observing); 

Conclusion:


Want to know more on what a Object.Observe() does?Have you ever noticed notifications on your phone and have you ever felt annoying ?Yes but some times these notifications tend to be useful and these can be implemented using Object.Observe().So go and check out how Object.Observe() makes all this.Since only chrome36 only supports Object.Observe() we should wait and see that all the other browsers all support this Object.Observe() to improve the performance in the browser display.Hopefully we will find a better and exciting observation ahead with Object.Observe().

Javascript getUserMedia API

Capturing Audio and Video in HTML5: 


Earlier were the days when internet started that people started using chat as a medium of communication in the mid 90's. People used to capture audio or video and then send it over the internet.These features required the use of plugins like flash and Silverlight and these two had certain technical problems.

With the emergence of WebRTC the plugins has made its way out. One of the API that is derived from WebRTC is getUserMedia API.

Javascript getUserMedia API

 Get started with getUserMedia API:


Several multimedia streams such as video, audio and both can be accessed from local devices.The users need not use additional plugins to access the video or audio.It helps the non-technical user to use the software without any additional plugins.However this API allows users to acquire the video and audio without having to send the data or storing it in a file. This API uses one method called as method.getUserMedia() which belongs to the window.navigator object.

Syntax :

   navigator.getUserMedia(constraints,successCallback,errorCallback); 

Constraints: 


It has a constraints parameter which is an object that has two properties called audio and video. The properties contain two values true and false. True means to request the stream and false means do not request the stream.

 Example: to request only video the parameter is as follows


    { 
        Video:true, 
        Audio:false 
     } 
Example -2: If the user wants a high resolution of 1280x720 of both audio and video and if the frame rate is 30 and if we want a frame rate of 60 then the following code could be used

    { 
        video:{ 
            mandatory:{ 
                 minWidth:1280, 
                 minHeight:720, 
                 minFrameRate:30 
            }, 
            optional:[{minFrameRate :60}] 
         }, 
         audio:true 
     }

successCallback:


The function on the calling application to invoke when passing the LocalMediaStream object. The getUserMedia() will call the successCallback using the LocalMediaStream object.

 Example :

     function(localMediaStream) { 
          var myvideo=document.querySelector(‘video’); 
          myvideo.src=window.URL.createObjectURL(localMediaStream); 
          myvideo.onloadedmetadata=function() { 
                 //play or do something with the video. 
          };
     },  

errorCallBack: 


The getUserMedia() function will call the function called as errorCallback with error codes as follows-
Permission_denied: The user is denied the permission to use a media device required for the operation. Not_supported_error: A constraint specified is not supported by the browser. Mandatory_unsatisfied_error: If no media tracks of the type specified in the constraints are found an error occurs.

 To get permissions:


To get getUserMedia() installable on the app the following code should be embedded inside the file-

      “permissions”:{ 
            “audio-capture”:{ 
                  “description”:”required to capture audio via getUserMedia” 
              } 
        } 

Compatibility of the browser: 


The getUserMedia() API is supported by the desktop browser but it’s performance of mobile browser is poor.The current browsers that support this API are Chrome, Opera and Firefox.Some browsers also have a security issue such that upon calling the getUserMedia() API, the browsers give an option to the user saying that the user can grant/deny access to the camera/mic.

Conclusion:


The getUserAPI() derived from WebRTC project has worked wonders in making web applications successful.This API is very flexible allowing user to select its own parameters such as the audio and the video streams.The compatibility among the browsers is not very good but it would increase eventually.

HTML5 Custom Elements (Web Components)

Introduction: 

If you have ever heard of the web and the components that make up the web, the elements that are going to bring about the change in the web technologies they  are  the ‘WEB COMPONENTS'. Web components are a combination of several connected technologies that make the elements reusable across the web.Until now the  web was revolving around Shadow DOM but now the there is transformation to the whole new concept called ‘Custom Elements’ wherein a user can create, define his own elements and its properties as well as behavior. 

What is this Custom Element all about? 
Inspite of the existing HTML tags such as <img>,<pre>,<video> <select> ,HTML5 gives us an opportunity to create our own tags and just use them as any other tag in the web application and  get the result we desire. 
Then how to create these Custom Elements ? 
When creating the custom elements we should make sure that we are not clashing with the existing or future HTML elements. 
Then what is the solution? 
Just define your custom element and put a hyphen somewhere in the name. 
 Example: <mypersonal-app> ........... </mypersonal-app> 
Once the element is decided we need to register it on the DOM, by passing the element as an argument to the JavaScript method called as registerElement() 
 Example: document.registerElement(‘mypersonal-app’); 
And now the DOM recognizes the newly defined custom element. 
Custom elements are basically classified into two interfaces – 
  1. HTMLUnknownElement 
  2. HTMLElement 
The former elements are those that are not registered and  not recognized by the DOM 
The latter elements are those that are registered and recognized by the DOM. 
It is possible to add our own properties and methods to a HTMLElement. It means that every custom tag can have its own API. 
To start up with this we need to initially define a new prototype and then add the properties and methods to it. 
Let us start up with an example by creating a new method called as 
fume() 

var perProto=Object.create(HTMLElement.prototype); 
perProto.fume=function() { 
     console.log(‘my first custom element’); 
}  
This method logs a message to the console. 
In the next step we need to register the element, stating that it should use our newly defined prototype 
         document.registerElement(‘mypersonal-app’,{prototype:perProto}); 

Once this is done, you can query your element in the DOM and call the method.

         var pers=document.querySelector(‘mypersonal-app’); 
         pers.fume(); 

Extending Existing elements to be used in this API: 
A user can use the existing HTML elements and use it in this API.Like if I want to extend the <img> element, I can do it in this way- 
       document.registerElement(‘mypersonal-app’,{ 
                                                    prototype:perProto, 
                                                    extends:’img’ 
       });  
The extends argument states that the custom element intends to use the img element 
          <img is=”mypersonal-app”>...</img> 

Now DOM has to be informed that the img element wants to be extended, using the is attribute 
Now this img element can have its own API. 
Some more specialities of Custom Elements:
A set of callback events are fired throughout the life cycle of custom elements such as 
  1. createdCallback: It is fired when an element is created 
  2. attachedCallback: It is fired when an element is attached to the DOM 
  3. detachedCallback: It is fired when an element is detached from the DOM 
  4. attributeChangedCallback: It is fired when an element is changed 
To run an anonymous function each time a new instance of custom tag is created in a page 

       perProto.createdCallback=function()  {....}; 

Do custom elements work with other Web Components? 
Custom elements have been completely designed to be interoperable with other features of the web components suite. 

For example one can include : template  element  such as 

     <mypersonal-app> 
           <template>...</template>
     </mypersonal-app> 

One can be ensured that the entire internal code is hidden by using shadow DOM and sharing across multiple websites is possible using HTML imports statement 

Which browsers support these custom elements: 
The chrome (version 33+) and Opera have made its way in displaying the custom elements in more efficient way. 

Conclusion: 

Here in this article we have seen how our own custom elements can be created and then used on the web just like any other HTML elements.This custom elements carves a niche for itself for future 
Web applications.With the use of shadow DOM and HTML it is going to make it’s  way through the development of the front-end web development application in a great way. 
So guys! Get yourself started to use them in your web applications  and bring in  a revolution in web development . 
Other links: