📜 ⬆️ ⬇️

25 tips to improve your jQuery code

This is a translation of an article written by Jon Hobbs-Smith . I found it quite interesting and decided to post it on my blog , as well as share it with desktop users, as well as I am interested in the jQuery library. Before you start, I want to note that it was written (as it was translated) by no means an expert in jQuery, so if you find an error in it, please report it. So, let's begin.

1. Download the library from Google Code

Google Code stores several popular Javascript libraries, including jQuery, and there are several ways to connect them to your site. I must say that they are loaded pretty quickly, besides, if a user has previously visited the site where the library is loaded in the same way as you have with Google, then the file will generally load from the cache.

You can load the library through an API specifically provided for this:
')



Or directly:



You can read more about connection methods here .

2. Use cheat sheets

And not just for jQuery. In the network now you can find a fairly large number of convenient cribs in many languages ​​and A4 libraries, so that it can for example be printed and hung on the wall next to the computer.

Here are links to a couple of these:
http://www.gscottolson.com/weblog/2008/01/11/jquery-cheat-sheet/
http://colorcharge.com/jquery/

In addition, we discussed the cheat sheets in one of the early posts .

3. Combine and compress your scripts

This is probably one of the top Javascript tips. This is especially true for projects that use a large number of plug-ins. Most browsers can not download script files at the same time, and sequential download significantly increases the total load time of the entire page. Therefore, it is recommended to collect all the files in one large script.

Do not forget to compress your code. Most plug-ins are already minimized, otherwise it is recommended to do this, especially since it will take you only a few seconds. For example, you can use Packer by Dean Edwards .

4. Use Firebug

If you haven't installed it yet, you just have to do it. In addition to such wonderful things as viewing http traffic and detecting problems in CSS, this add-in keeps an excellent command log that can help you detect errors in your scripts.

Here you will find a detailed description of all its features.

“Console.info” is very useful, with which you can display messages and variable values ​​on the screen without using alerts, as well as “console.time”, which allows you to track the execution time of certain code sections. They are all quite easy to use.

console.time('create list');

for (i = 0; i < 1000; i++) {
var myList = $('.myList');
myList.append('This is list item ' + i);
}

console.timeEnd('create list');


In this case, I deliberately wrote a deliberately inefficient code. Next we will see how you can use the timer to show the effectiveness of making improvements.

5. Cache your selectors.

The selectors in jQuery are awesome. Using them is very easy to select elements on the page, but if you use them very intensively in your script, this can significantly slow down the page.

If you always refer to the same selector, you can simply memorize it and then use it as long as you like, without fear of harming the speed. Let's see the following code:

for (i = 0; i < 1000; i++) {
var myList = $('.myList');
myList.append('This is list item ' + i);
}


Running this simple code took 1066 milliseconds on my computer in FF3 (imagine how long it would have been running in IE6!). Now let's execute the similar code, but use the selector only once:

var myList = $('.myList');

for (i = 0; i < 1000; i++) {
myList.append('This is list item ' + i);
}


And what do you think? Only 224 milliseconds, more than 4 times faster, and in fact we moved only one line of code :-)

6. Keep DOM manipulation to a minimum.

We can speed up the code from the previous board, minimizing work with the DOM. DOM operations such as .append (), .prepend (), .after () and .wrap () are very expensive and frequent use of them can also increase the execution time of your code.

All that is required in our case is to use string concatenation to build the list, and then use the .html () method once and our code will become noticeably faster. Let's see an example.

var myList = $('#myList');

for (i=0; i<1000; i++){
myList.append('This is list item ' + i);
}


It took 216 milliseconds to complete on my computer, only 1/5 of a second, but if we first build the list as a string, then use the HTML method to insert as follows:

var myList = $('.myList');
var myListItems = '';

for (i = 0; i < 1000; i++) {
myListItems += 'This is list item ' + i + '';
}

myList.html(myListItems);


That such script will be executed already 185 milliseconds, 31 milliseconds faster. What-no, but still time savings, and in the case of more complex code, the efficiency will be more tangible.

7. Wrap everything in one item before working with the DOM.

I can not explain why this works, but for sure the experts in jQuery will give an answer to this.

The point is this. In our last example, we inserted 1000 list items into one unordered list item using the .html () method. If we first wrapped them in a UL tag before insertion, and then the already formed list was inserted into another tag, for example DIV, then it would be much more efficient and faster than inserting 1000 elements. Let's see an example so that everything becomes clear ...

var myList = $('.myList');
var myListItems = '<ul>';

for (i = 0; i < 1000; i++) {
myListItems += '<li>This is list item ' + i + '</li>';
}

myListItems += '</ul>';
myList.html(myListItems);


This code is executed in just 19 milliseconds, almost 50 times faster than our very first example.

8. Use identifiers instead of classes.

In jQuery, class selectors are just as convenient as selectors by identifier, which made them equally popular. But it is still better to select elements by ID, since jQuery uses the getElementByID method for this browser, rather than some of its own methods. Let's see an example.

I will use the previous example, but I will slightly modify it so that each element of the list will have its own unique class. Then we will go over the entire list and look at each element in the class.

//
var myList = $('.myList');
var myListItems = '<ul>';

for (i = 0; i < 1000; i++) {
myListItems += '<li class="listItem' + i + '">This is a list item</li>';
}

myListItems += '</ul>';
myList.html(myListItems);

//
for (i = 0; i < 1000; i++) {
var selectedItem = $('.listItem' + i);
}


As I expected, this task noticeably loaded my browser. In total, the execution time of the code was 5066 milliseconds (more than 5 seconds). Then I changed the code and asked each element of the list its own identifier instead of a class, and then I addressed each element by its ID.

//
var myList = $('.myList');
var myListItems = '<ul>';

for (i = 0; i < 1000; i++) {
myListItems += '<li id="listItem' + i + '">This is a list item</li>';
}

myListItems += '</ul>';
myList.html(myListItems);

//
for (i = 0; i < 1000; i++) {
var selectedItem = $('#listItem' + i);
}


This code was executed only 61 milliseconds. Almost 100 times faster.

9. Set context in selectors.

By default, when you use any selector, such as $ ('. MyDiv'), the entire DOM structure will be analyzed in its search, which on large pages can be quite expensive.

In such cases, we must not forget that when building a selector, the second parameter can be set:

jQuery(, )

By setting the context parameter, you specify in which element to search for the required element, thus jQuery does not have to look through the entire DOM structure.

To demonstrate this, take the first block of code from the previous example. It creates an unsorted list of 1000 items, each with its own class. Then he goes over the whole list to each class. This operation took about 5 seconds to sort through each element in this way.

var selectedItem = $('#listItem' + i);

Then a context parameter was added that only made the selector inside an unnumbered list:

var selectedItem = $('#listItem' + i, $('.myList'));

Execution of this code took 3818 milliseconds, which is 25% faster. But we again made only a small change in the code.

10. Use chains

One of the most notable features in jQuery is the ability to use chains of methods. So, in the following example, we will change the class of the element.

$('myDiv').removeClass('off').addClass('on');

Do not forget that the code works great with line breaks (after all, jQuery = JavaScript), and this allows you to make your code more neat and readable, for example, as in the following example.

$('#mypanel')
.find('TABLE .firstCol')
.removeClass('.firstCol')
.css('background' : 'red')
.append(' !');


It is worth noting that the habit of using a chain of methods helps you to reduce the code in the use of selectors.

But that is not all. And what if you want to apply a series of functions to an element, but one of them changes the appearance of the element, for example, as in the following code ...

$('#myTable').find('.firstColumn').css('background','red');

We chose a table, found in it cells of the firstColumn class and painted them red.

And now let's paint all the cells of the lastColumn class in blue? Because we used the find () method, we filtered out all the elements from the set that do not have the firstColumn class, so we need to use this selector again to select the desired table elements and cannot continue the chain of methods. Fortunately, jQuery has a end () method that allows you to return to the previous set of elements, as in the following example.

$('#myTable')
.find('.firstColumn')
.css('background','red')
.end()
.find('.lastColumn')
.css('background','blue');


In addition, writing your own function, which can be used in a chain, is much easier than you think. To do this, it is enough to follow up on the completion of all actions with the item return it.

$.fn.makeRed = function() {
return $(this).css('background', 'red');
}

$('#myTable').find('.firstColumn').makeRed().append('');


Isn't it all simple enough?

11. About the animate () method

When I first started using jQuery, I really liked the already defined animation methods, such as slideDown () and fadeIn (), with which you could simply and quickly make amazing effects. Each of these functions is based on the animate () method, which is very functional and also very easy to use.

slideDown: function(speed,callback){
return this.animate({height: "show"}, speed, callback);
},

fadeIn: function(speed, callback){
return this.animate({opacity: "show"}, speed, callback);
}


The animate () method simply changes various CSS properties from one value to another. Thus, you can change the height, width, transparency, background color, various indents and everything else you wish.

For example, this is how you can easily animate your menu by changing the element height to 100 pixels when you hover the mouse.

$('#myList li').mouseover(function() {
$(this).animate({"height": 100}, "slow");
});


Unlike other jQuery functions, the animation automatically queues for execution, i.e. if you want to start one animation after another, you just need to call the animation twice, without any callbacks. In the example, the height will begin to change as soon as the width changes.

$('#myBox').mouseover(function() {
$(this).animate({ "width": 200 }, "slow");
$(this).animate({"height": 200}, "slow");
});


If you want the animation to run in parallel, simply put both styles in the parameter object of the method call, for example, as in the following example.

$('#myBox').mouseover(function() {
$(this).animate({ "width": 200, "height": 200 }, "slow");
});


You can always animate properties with numeric values. In addition, you can download a plugin that will help you animate properties whose values ​​are not numbers, such as font or background colors .

12. Delegation of events

Using jQuery makes it very easy to bind events to DOM elements, which is great, but binding a large number of events is irrational. Delegation of events allows you to achieve the desired result in many situations with the help of linking fewer events. Let's see an example.

$('#myTable TD').click(function(){
$(this).css('background', 'red');
});


A simple click function colors the table cells in red. And now imagine, if we have a table of 10 columns and 50 lines, it turns out we bind the event to 500 elements. But what if we could bind the event to the table, and then, by clicking on the table, we determined which cell to paint in red?

This is exactly what is called event delegation. Let's see how it works.

$('#myTable').click(function(e) {
var clicked = $(e.target);
clicked.css('background', 'red');
});


'e' contains information about the event, including the object on which the mouse was clicked. All that is required of us is to determine which particular cell the user clicked.

In addition, the delegation of elements has another plus. Usually, when you bind an event to any elements, it is bound to these elements and no more. If during the work of the page you added new elements to the DOM, which also correspond to the selector, then the handler will not be applied to them anymore. In the case of delegation, you can add as many elements as you like to the DOM after binding the event and there will be no problems with them.

13. Use classes to store states

This is the easiest way to store information about a block of html code. jQuery is good for manipulating elements using classes, so if you need to store information about the state of an element, why not use a special class for this purpose?

In the following example, we will create a drop-down menu. By clicking on the layer of the button class, the submenu (panel class) will drop out via slideDown () if it is not shown or hide through slideUp () if it is the other way round open. So let's start with HTML.

<div class="menuItem expanded">
<div class="button">

</div>
<div class="panel">
<ul>
<li> 1</li>
<li> 2</li>
<li> 3</li>
</ul>
</div>
</div>


Very simple! Now add a special class that will store the state of the submenu. As a result, we will only need to write a click handler for the diva of the button class, which will hide or show our submenu using slideUp () and slideDown (), respectively.

$('.button').click(function() {

var menuItem = $(this).parent();
var panel = menuItem.find('.panel');

if (menuItem.hasClass("expanded")) {
menuItem.removeClass('expanded').addClass('collapsed');
panel.slideUp();
}
else if (menuItem.hasClass("collapsed")) {
menuItem.removeClass('collapsed').addClass('expanded');
panel.slideDown();
}
});


This is a very simple example, but you can add special classes to store any necessary information about any fragment of HTML code.

As a rule, this approach is used in simple cases. In more complex it is better to refer to the content of the following advice.

14. Use the built-in data () method to store data.

For some reason, the function described below is not well documented, but nevertheless jQuery has a built-in data () method that can be used to store key-value type information for any DOM element. Let's see an example of its use.

$('#myDiv').data('currentState', 'off');

We can refine the example from the previous board. We will use the same HTML code, but for data storage we will use the data () method.

$('.button').click(function() {

var menuItem = $(this).parent();
var panel = menuItem.find('.panel');

if (menuItem.data('collapsed')) {
menuItem.data('collapsed', false);
panel.slideDown();
}
else {
menuItem.data('collapsed', true);
panel.slideUp();
}
});


I think you will agree that this will be better. For more information about the data () and removeData () methods, you can visit the jQuery documentation section .

15. Write your selectors

JQuery has a large number of built-in selectors. But what do you do when you need to select elements on some basis for which there are no solutions in jQuery?

Of course, you can assign classes to them initially and then access these elements through it. But it is not so difficult to create your own selector.

Let's see an example.

$.extend($.expr[':'], {
over100pixels: function(a) {
return $(a).height() > 100;
}
});

$('.box:over100pixels').click(function() {
alert('The element you clicked is over 100 pixels high');
});


The first block of code creates a selector that selects all elements that are more than 100 pixels high. The second block is used to bind a click handler to such elements. You can develop this topic further, but I think you have already noticed how powerful this tool is and you will easily find a large number of other samopisnyh selectors on Google.

16. Simplify HTML and modify it when loading

The title is quite meaningful, but this tip can improve the look of your code, reduce weight and load time, and help you with SEO to some extent. Let's see the following HTML code for an example.

<div class="fieldOuter">
<div class="inner">
<div class="field"> 1</div>
</div>
<div class="errorBar">
<div class="icon"><img src="icon.png" alt="icon" /></div>
<div class="message"><span> </span></div>
</div>
</div>
<div class="fieldOuter">
<div class="inner">
<div class="field"> 2</div>
</div>
<div class="errorBar">
<div class="icon"><img src="icon.png" alt="icon" /></div>
<div class="message"><span> </span></div>
</div>
</div>


This is an example of a form markup, slightly modified for clarity. I’m sure you will agree that the code doesn’t look very nice, and if the form is large, you will get a less annoying page. Agree, the following code looks much better.

<div class="field"> 1</div>
<div class="field"> 2</div>
<div class="field"> 3</div>
<div class="field"> 4</div>
<div class="field"> 5</div>


All that is required of you now is to use jQuery to put duplicate code fragments back into place.

$(document).ready(function() {
$('.field').before('<div class="fieldOuter"><div class="inner">');
$('.field').after('</div><div class="errorBar"><div class="icon">
<img src="icon.png" alt="icon" /></div><div class="message">
<span> </span></div></div></div>');
});


It is not always advised to do this, because loading a code fragment can be noticeable when loading a page, but in some cases, when you have a lot of duplicate HTML code, this advice will help reduce the weight of your page, as well as the advantages in SEO when reducing duplicate fragments are obvious .

17. Uploading content for speed and SEO

Another way to speed up the loading of your page and make HTML more readable is to load entire code fragments using AJAX requests after the page has finished loading. Users will eventually get what they need, and search robots will see only what you want to show them.

This can be done as in the following example ...

$('#forms').load('content/headerForms.html', function() {
//
});


I think everything is clear here, we will not particularly stop.

Of course, again, you should not use this advice everywhere. It should be understood that this creates an additional load on the server, and also a part of your page may be unavailable for some time for the user. But when used properly, it can serve as a good optimization technique.

18. Use jQuery functions

jQuery is not only for creating cool animation effects. The developers have built in the library several really useful methods that can compensate for some of the flaws of the JavaScript functionality in general.

http://docs.jquery.com/Utilities

In particular, some browsers do not support functions for working with arrays defectively (for example, IE7 doesn't even support the indexOf () method). jQuery has methods for iterating, filtering, cloning, merging and removing duplicates from arrays.

Another common problem is the difficulty of getting the selected item in the drop-down list. In regular JavaScript, you cannot get a SELECT element via getElementByID, get its children as an array and walk through them, determining which one is selected and which one is not. jQuery easily solves this problem ...

$('#selectList').val();

Therefore, it is better to lose some time and dig into the jQuery documentation on the main site, reading about other little-known, but very useful features.

19. Use noconflict when working with other libraries.

Most javascript libraries use the $ symbol for their own purposes, which can cause errors when using more than one framework on one page. Fortunately, this problem is simply solved using the .noconflict () method, as in the following example.

var $j = jQuery.noConflict();
$j('#myDiv').hide();


20. How to know that the picture has loaded

This is another one of those problems that is not well documented, as it is worth it, but nevertheless it often comes up when building photo galleries, carousels, etc., and in fact is solved quite simply.

All that is required is to use the .load () method for the IMG element and the callback function to complete the download in it. In the following example, the src attribute in the image tag is modified to load a new image and a simple upload function is bound.

$('#myImage').attr('src', 'image.jpg').load(function() {
alert(' ');
});


As you understand, the alert will appear at the end of the picture download.

21. Always use the latest version.

jQuery is constantly improving, and its creator John Resig (John Resig) is constantly looking for ways to improve the performance of the library. In this regard, it is recommended to constantly monitor the framework updates (stable versions) and update your working version.

22. How to verify that an item exists

There is no need to check whether an element is on the page before performing any actions on it, because jQuery will simply ignore actions on a non-existent DOM element. But if you really need to check if something was selected and in what quantity, use the length property.

if ($('#myDiv).length) {
//
}


Simple and obvious.

23. Add JS class to HTML tag

(Karl Swedberg).

jQuery JS HTML.

$('HTML').addClass('JS');

JavaScript , CSS …

.JS #myDiv{display:none;}

, JavaScript jQuery , ( , ). JavaScript ( ) .

24. «false»

, - . …

!

… - , …

$('popup').click(function(){
// -
});


… , , , # .

, «return false;» , …

$('popup').click(function(){
// -
return false;
});


25. ready

$(document).ready, , .



$(document).ready(function (){
//
});




$(function (){
//
});


Thanks for attention.You can also find this and other jQuery posts on my blog dedicated to this library . Besides, I will always be glad to see you among my followers on Twitter .

Source: https://habr.com/ru/post/63797/


All Articles