Jquery Tips and Tricks

What are some quick tips for increasing jQuery performance?

  1. Prefer simple selection first only by ID, and second only by tag name. Selecting by class name or CSS selector requires jQuery to walk the DOM, while ID and tag map to "native" browser DOM functions (getElementById and getElementByTagName).
  2. Cache your jQuery objects as much as possible.
  3. Scope your operations to a root jQuery object. Rather than selecting elements individually, select a common ancestor element and use the find function to find elements within the scope of that elements children. This is really only optimal if you are performing some operations on the common ancestor anyway; otherwise the overhead of finding the ancestor and caching it may outweigh the benefit of scoped traversal.
  4. Don't use $.each(), use for(;;) instead. It's over ten times faster.

jQuery pitfalls to avoid

Being unaware of the performance hit and overusing selectors instead of assigning them to local variables. For example:-

$('#button').click(function() {
$('#label').method();
$('#label').method2();
$('#label').css('background-color', 'red');
});

Rather than:-

$('#button').click(function() {
var $label = $('#label');
$label.method();
$label.method2();
$label.css('background-color', 'red');
});

Or even better with chaining:-

$('#button').click(function() {
$("#label").method().method2().css("background-color", "red");
});

I found this the enlightening moment when I realized how the call stacks work.

Edit: incorporated suggestions in comments.

Good tips and tricks to streamlining your Javascript and jQuery

A very good technique to help minifiers, is to pass variables into a self invoking function:

(function(window, document, $, undefined) {
// all of your application logic goes in here
}(window, window.document, jQuery));

A minifier will then create shortcuts for the arguments, like a, b, c, d.

(function(a, b, c, d) {
}(window, window.document, jQuery));

Now, window, document and jQuery (if it's used) and the undefined value are accessed quite often normally. This will help to decrease the filesize even more.

A few nice Javascript shortcuts, are described in this article.

For instance, use ~~ instead of Math.floor().

var floored = Math.floor(55.2115);  // = 55

var floored = ~~(55.2115);  // = 55

Another really neat thing is, that almost all Javascript interpreters convert numbers for you. For instance, we want to have a setTimeout which fires after 3 minutes. Instead of doing it like

setTimeout(function() {
}, 180000);

or 60 * 3 * 1000, we can just call:

setTimeout(function() {
}, 18e4);

Which probably makes much more sense, on much bigger numbers, but anyway :-)

jquery tipsy two tips in the same time

As @Garath asked plugin does not support two tool tip on same element, but you can do it another way.. warp <a> element by <span> and apply another tool tip on <span> element

    <span rel="17 tweets" class="tip-s">
<a class="twitter tip-n" target="_blank" href="http://twitter.com/intent/tweet?text=text&url=page" title="Twitter">ICON</a>
</span>

<script type="text/javascript">
$(function(){
$('.tip-n').tipsy({fade: true, gravity: 's', html: true});
$('.tip-s').tipsy({fade: true, gravity: 'n', html: true, title: 'rel'})
});

</script>

$(function(){  $('.tip-n').tipsy({fade: true, gravity: 's', html: true});  $('.tip-s').tipsy({fade: true, gravity: 'n', html: true, title: 'rel'})})
<link href="http://onehackoranother.com/projects/jquery/tipsy/stylesheets/tipsy.css" rel="stylesheet"/><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script><script src="http://onehackoranother.com/projects/jquery/tipsy/javascripts/jquery.tipsy.js"></script><br/><br/><br/><br/><span rel="17 tweets" class="tip-s"><a class="twitter tip-n" target="_blank" href="http://twitter.com/intent/tweet?text=text&url=page" title="Twitter">ICON</a></span>

Tips for single JQuery page supporting both Desktop and Mobile?

CSS Media Queries are great for this. (beware, they're CSS3) based on the size of the viewing agent (and it updates dynamically!) certain content can be hidden or displayed, making it basically a morph of your options #1 and #2. You'd have a big full featured layout for desktop, with it's styling and jQuery, and when the screen is small (meaning it's a phone or a nerd resizing his browser) you hide some of the more detailed stuff and restyle a few things and maybe display a few other things.
Read about Media Queries here: http://ie.microsoft.com/testdrive/HTML5/CSS3MediaQueries/Default.html
EDIT: Just to clarify, you can completely customize elements with media queries, so, at desktop size, a div might have a dotted border, rounded corners, 10px padding, etc., whereas on the phone the div has 1px padding, solid border, etc.

Some questions about the 25 jquery tips

9 - Give your selectors a context:

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

v/s

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

According to the article the first one should be faster. But I can't see how this can be...

First of all accessing by ID is one of the fastest ways to get to an element. It's just a lookup from global ID-s hash table. Adding a context to it should add no speed. Looking up the context should take some extra time and therefore the first example should be slower.

I also did some measurements and found that indeed the first one is many times slower.

As for this:

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

That should be about the same speed as the first one. And according to my measurements it is indeed about the same, just a little faster.

But the specifying context can be beneficial when dealing with other types of selectors and especially you reuse it, like that:

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

In this example it gives you a considerable speed boost.

Like with everything else related to performance - you have to measure before you know if something applies in your specific situation.

How many handlers is the time when you should start using event delegation?

When I feel that the page is slow. 99% of the time normal event handlers are good enough.



Related Topics



Leave a reply



Submit