jQuery Performance Tips

http://dumitruglavan.com/jquery-performance-tips-cheat-sheet/

Some notes from reddit:

#6 There is little to no performance difference between a cached selector and chaining. The ONLY difference would be shorter code (less bandwidth used?).

#9 This is just plain wrong. DOM manipulation can be extremely fast if you know what you are doing. He uses this example

The faster way to do this would be

frag = $('<ul id="menu"></ul>');
listItem = $('<li></li>')
for (var i = 1; i < 100; i++) {
  frag.append(listItem.clone().text(i));
}
$('#header').prepend(frag);

#14 Use jQuery’s utility functions
“.each(), for example, relies on anonymous function calls. This can be REALLY slow”

#15 not really much of a performance tip
#16 is REALLY finicky and hard to profile.

Google event tracking

$(document).ready( function() {
    // add an event to all link for google analytics
    $('a').click(function () {
        // tell analytics to save event
        try {
            var identifier=$(this).attr('id') ;
            var href=$(this).attr('href')
            var label="";
            if ( typeof( identifier ) != 'undefined' ) {
                label=label+'[id]:'+identifier
                category='JSLink'
            }
            if ( typeof( href ) != 'undefined' ) {
                label=label+' [href]:'+href
                if ( href[0] == '#' ) {
                    category='Anchor';
                } else {
                    category='Link';
                }
            }
            _gaq.push(['_trackEvent', category, 'clicked', label]);
            // console.log('[tracked]: ' + category + ' ; clicked ; ' + label );
        }
        catch (err) {
            // console.log(err);
        }

        // pause to allow google script to run
        var date = new Date();
        var curDate = null;
        do {
            curDate = new Date();
        } while (curDate-date < 300);
    });
});

Source: External blog

Performance difference in JavaScript

LearningjQuery has an interesting article about different speeds of show and hide html elements.

From fast to slow:

  • Enabling/Disabling a stylesheet
  • .css(‘display’, ”), .css(‘display’, ‘none’)
  • addClass(), .removeClass()
  • .show(), .hide()
  • .toggle()
  • jQuery toggle seems to fail pretty bad speed wise, while the “Enabling/Disabling a stylesheet” seems to be such an usual approach and probably make it confusing to a lot web develoeprs (yours truly included: would have said WTF if hadn’t read the article).

    I’d go with .css(‘display’, ”), .css(‘display’, ‘none’) in the case where performance is important (i.e. multiple, alot of layers to be hidden or shown), and in other case, .show()/hide() or even toggle() seems to be fine to me. “Program Readability” > “Performance” in a lot of situations.