This article explains the things already known to us. In jQuery, we can do similar things in several ways. However, there are differences in performance of each approach. As a web developer, we need to use the best suitable approach for improving the performance.
I have used JSFiddle and jsPerf for demo purposes and also provided the links in respective sections. You need to click on the “Run Tests” button on “jsperf” to check the difference in performance. Sometimes, you may find the demo working to contradict with the article. But, nothing to worry about, since this happens due to network issues. So, just be patient and run it once again to see a proper response.
Use the latest version of jQuery
It's always good to use the latest jQuery version in your web application. But, some earlier plugins in your application might not be compatible with the latest version of jQuery. This issue is usually found in Internet Explorer (IE) and the compatibility issues may arise in IE8 or prior versions. IE8 or below are compatible with jQuery1.* versions. So, we need to have a mechanism to load jQuery1.11.2 (the latest in jQuery 1.*) and for others the latest jQuery version.
- [if lt IE 9]
- <script src=”http:
- [endif]
- [if gte IE 9]
- <script src=”http:
- [endif]
If it's an Internet Explorer (IE) version less than 9 then
jquery-1.11.2.js will be loaded. If it's greater than or equal to 9,
jquery-2.1.3.js will be loaded. Here, we fixed an issue with IE. Now, other browsers will load both the jQuery files. However, the later will be put in effect, but unnecessarily we are loading 2 JavaScript files that will cost our site's performance.
Here is a syntax designed by Microsoft that is only understood by Internet Explorer. We can get its help to avoid the preceding issue.
- <!--[if lt IE 9]>
- <script src=”http:
- <![endif]-->
- <!--[if gte IE 9]><!-->
- <script src=”http:
- <!--<![endif]-->
Browsers other than IE just can't understand the first block. So, the first if-block will be ignored (considered as white space). In the second if block, the script tag is outside the comment. So, its easier for the web browsers to understand.
Web browsers other than IE will read it as:
- <!--
- <script src=”http:
- - ->
- <!-- -->
- <script src=”http:
- <!-- -->
So, IE will load jQuery based on the IE version and the condition specified. IE 8 or less will load jquery-1.11.2.js and IE9 or more and other browsers will load jquery-2.1.3.js.
Use CDN
It's always a good practice to use Content Delivery Network (CDN) over local jQuery files. But, what if CDN is down? Your site will not function properly. Not to worry, we have a way to overcome it.
Load the jQuery file from CDN. Check if it's loaded or not; load it from local, if it's not yet loaded. Here's the code.
- <script src=”http:
- <script>
- window.jQuery || document.write('<script src=”~/Js/jquery-2.1.3.js”><\/script>')
- </script>
Selector Preference
- Try to use ID since it gives the best performance $('#elementId').
- Performance-wise, next comes the tag selector $('tag').
- Avoid selection by class. Class selectors are the slowest $('.elementClass').
- If you need to use a class selector, use it with it's tag or parent elements.
Increase specificity from left to right, not right to left.
Use:
Instead of:
$.find()
- Use find() instead of specifying the context explicitly.
Use:
- $('#Mydiv').find('label.myClass').hide()
Instead of:
- $('#Mydiv label.myClass').hide()
The preceding code will provide the same result, but the former one is faster.
find method
jQuery uses the Sizzle engine for pseudo classes like :not and :last. Try not to force jQuery to use it.
Cache the SelectorWhen you need to perform some jQuery operations on a specific element, it's better to keep the selected element in a JavaScript variable and operate on it, instead of getting the required element each time you need to operate on it.
Instead of:
- $('#Mydiv label.myClass').html('My label');
- $('#Mydiv label.myClass').css('border','1px solid red');
- $('#Mydiv label.myClass').show();
Use:
- var SelElement = $('#Mydiv label.myClass');
- SelElement.html('My label');
- SelElement.css('border','1px solid red');
- SelElement.show();
cache selectorChainingTake advantage of jQuery chaining. You can perform multiple jQuery operations on the selected element at once in a single line. It is faster than performing operations one-by-one.
Instead of
- var SelElement = $('#Mydiv label.myClass');
- SelElement.html('My label');
- SelElement.css('border','1px solid red');
- SelElement.show();
Use
- $('#Mydiv label.myClass').html('My label').css('border','1px solid red').show();
GroupUp Selectors
When you need to perform same operation on a list of elements, it's always recommended to group those elements and operate on the group.
Instead of:
- $('#divTest').hide();
- $('p').hide();
- $('label.myClass').hide();
Use:
- $('#divTest, p, label.myClass').hide();
GrouppingDOM Manipulation
When you need to add some elements to the DOM, it's always a good idea to form the entire HTML first, then add to the DOM, instead of appending the HTML step-by-step.
- <div id='myDiv'></div>
-
- var Details = [
- {Id:1, Name: “ABC”, Standard:1},
- {Id:2, Name: “MNO”, Standard:1},
- {Id:3, Name: “PQR”, Standard:2},
- {Id:4, Name: “STU”, Standard:5},
- {Id:5, Name: “XYZ”, Standard:9}
- ];
-
- var Element = $('#myDiv');
Instead of:
- Element.append('<table>');
- $.each(Details, function(k,v){
- Element.append('<tr>');
- Element.append('<td>' + v.Id + '</td>');
- Element.append('<td>' + v.Name + '</td>');
- Element.append('<td>' + v. Standard + '</td>');
- Element.append('</tr>');
- });
- Element.append('</table>');
Use:
- var strHtml = '<table>';
- $.each(Details, function(k,v){
- strHtml += '<tr>';
- strHtml += '<td>' + v.Id + '</td>';
- strHtml += '<td>' + v.Name + '</td>';
- strHtml += '<td>' + v. Standard + '</td>';
- strHtml += '</tr>';
- });
- strHtml += '</table>';
- Element.html(strHtml);
Dom manipulation$.detach(), hide(), empty(), remove()
detach() is a new jQuery function. It will just detach the selected element from the DOM. The element, all it's properties and events are still there, but you can't use it. Don't be confused with hide(), empty(), remove() and so on. Here is a comparison.
- Hide makes display:none. But the element is still there in DOM.
- In case of detach(), the element is no longer there in the DOM, but it exists. All it's properties, attributes, events and so on are still attached with the element. When there is a need, you can again append it to it's parent or wherever you want to.
- empty() removes child elements of the selected element.
- remove() removes the elements themselves and hence all it's child elements are also removed.
- var MyTable = $('#MyTable');
- var ParentElement = MyTable.parent();
- MyTable.detach();
-
- ….
ParentElement.append(MyTable);
Group Up your CSSWhen you have a set of styles to apply on some elements, it's always recommended to group up all the styles and apply on the element at once.
- Var MyDiv = $('#MyDiv');
- Instead of
- MyDiv.css('border', '1px solid black');
- MyDiv.css('color', 'red');
- MyDiv.css('backgroun-color', 'green');
- MyDiv.css('display', 'block');
Use:
- MyDiv.css({'border': '1px solid black', 'color': 'red', 'backgroun-color': 'green', 'display': 'block'});
Group StyleInstead of:
- MyDiv.css('backgroun-color', 'white');
- if(Cond)
- {
- MyDiv.css({ 'color': 'red', 'border', '1px solid red'});
- }
- else
- {
- MyDiv.css({ 'color': 'green', 'border', '1px solid green'});
- }
Use:
- var Css = {'backgroun-color': 'white'}
- if(Cond)
- {
- Css .color = 'red';
- Css.border = '1px solid red';
- }
- else
- {
- Css .color = 'green';
- Css.border = '1px solid green';
- }
- MyDiv.css( Css);
Style is better than CSS
css() works fine when you need to put style on fewer elements. But, when you need to put a specific style on more than 20 elements, a style in the head tag will provide better performance than adding CSS.
Instead of:
- $('div').css({ 'color': 'red','width': '200px','height': '200px',
- 'border': '1px solid','margin-left': '10px','position': 'relative','display': 'block'
- });
- Use
- $("<style type=\"text/css\">div { color: red,\width: 200px,\height: 200px,\
- border: 1px solid,\margin-left: 10px,\position: relative,\display: block }</style>")
- .appendTo("head");
Style vs CSSEvent Delegation/Propagation
- <div id='divOuter' style='border:1px solid red; width:500px; height:300px;'> divOuter
- <div id='divMiddle' style='border:1px solid green; width:400px; height:200px;'> divMiddle
- <div id='divInner' style='border:1px solid blue; width:300px; height:100px;'> divInner</div>
- </div>
- </div>
-
- $('div').click(function(){
- alert($(this).attr('id'));
- });
RasmitadashIf you click on the inner-most div, you will get 3 alerts. If you click on the middle div, you will get 2 alerts. If you click on the outer-most div you will get a single alert. This is because when you fire an event, it propagates to it's parent, then the parent's parent ... and finally to the root. That means, when you click an element, you are effectively clicking the entire document. This is called event bubbling or propagation.
We have a way to prevent this event propagation.
- $('div').click(function(e){
- e.stopPropagation()
- alert($(this).text());
- });
hr2 gampBind Event dynamically
There are several ways to bind an event to an element dynamically; .bind(), .on() and .delegate().
.bind()
- $('#ulItems li label').bind('click', function(){
- alert($(this).text());
- });
The shorthand representation of .bind() is as follows.
- $('#ulItems li label').click(function(){
- alert($(this).text());
- });
- bind() attaches the event upfront. So, it can have performance issues on page load.
- bind() not only wires up quickly, but the event handler is invoked immediately when the event is fired.
- bind() will not attach the event handler to the dynamically added matching elements.
.delegate()
- $('#ulItems').delegate(' li label', 'click', function(){
- alert($(this).text());
- });
- delegate() attaches events to the root level element (here #ulItems) and to the selected elements as well. When an event is bubbled or delegated or propagated to a parent element, jQuery checks the event metadata to determine which event handler should be invoked. This extra work makes the performance slower with respect to user interaction.
- The event bind is not done upfront. So, initial registration process is speedy.
- As event is bound to the parent element, therefore it affects the dynamically bound elements as well.
.on()
- .on() can mimic for .bind(), .delegate(), .live(). It's behavior depends on the parameters ed.
- $('#ulItems').on('click', ' li label', function(){}); => $('#ulItems').delegate(' li label', 'click', function(){});
- $('#ulItems li label').on('click', function(){}); => $('#ulItems li label').bind('click', function(){});
Event delegation
- <div>
- <ul id='ulItems'>
- <li><label>Item #1</label></li>
- <li><label>Item #2</label></li>
- <li><label>Item #3</label></li>
- </ul>
- </div>
-
- $('#ulItems li label').click(function(){
- alert($(this).text());
- });
-
- Now, let's add a 'li' element.
- $('#ulItems').append('<li><label>Item #4</label></li>');
http://jsfiddle.net/rasmitadash/k7435o18/Now, when you click on this newly added label, you will not get any alert. Because, when you registered this event, the element was not there, it was added after the event was registered.
To make the dynamically bound events effective on dynamically bound elements, bind an event to the parent element and delegate it to the required element. Let us see an example.
- $('#ulItems').delegate(' li label', 'click', function(){
- alert($(this).text());
- });
http://jsfiddle.net/rasmitadash/vwp2erxc/ing data to Event handler
- function Greet(event)
- {
- alert(event.data.name)
- }
-
- $('#ulItems li label').click({name: “Rasmita”}, Greet);
rasmitadashBinding multiple Events
- $('#Mydiv').on({
- click: function(){
- alert(“clicked”);
- },
- mouseenter: function(){
- alert(“mouse enterd”);
- },
- mouseleave: function(){
- alert(“mouse left”);
- }
- });
rasmitadashattr() vs prop()
- An attribute value may only be a string, whereas a property can be of any type. For example, the”checked”property is a Boolean, the”style” property is an object with individual properties for each style, the “size”property is a number.
- If a property and attribute have the same name, usually updating one will update the other, but this is not the case for certain attributes of inputs, such as “value” and “checked”. For these attributes, the property always represents the current state, whereas the attribute (except in old versions of IE) corresponds to the default value of the input.
So, “attribute value” holds the default value of the input control. If the user changes a value, the “property value” changes, but not the “attribute value”. Therefore, for a default value we use the .attr() function and for the latest value of HTML elements (such as inputs, checkbox's, radios and so on) use the .prop() function.
rasmitadash etz3
Binding events in loop
Avoid implementing an event handler body with the event itself. Instead, create a separate handler function and call the handler with a parameter.
rasmitadashq8714
rasmitadash7awz6
Instead of:
- $(function(){
- var ArrLabel = $('label'), len = ArrLabel.length;
- for(i=0; i<len;i++){
- $(ArrLabel[i]).on('click',function(){
- alert(i);
- });
- }
- });
Use:
- $(function(){
- function myclickhandler(j){
- return function(){
- alert(j);
- }
- }
-
- var ArrLabel = $('label'), len = ArrLabel.length;
- for(i=0; i<len;i++){
- $(ArrLabel[i]).on('click',myclickhandler(i +1));
- }
- });