Showing posts with label performance. Show all posts

Russian CDN for jQuery

I recently discovered that the biggest Russian search engine Yandex (yeah, it’s bigger than Google in Russia) is using jQuery on its home page. It also hosts all previous jQuery versions on it’s fast gzip enabled servers just like Google and MIcrosoft do.

Because most of the Russian internet users have visited Yandex already, they already have it in their browser cache. I also did route tracing from Russian server to Google CDN servers and I was directed to the server in California, USA and pining the local Russian CDN server was at least 3 times faster.

Anyway, if you decide to use Russian CDN to host your jQuery files here are the links:

Minified versions
http://yandex.st/jquery/1.2.6/jquery.min.js
http://yandex.st/jquery/1.3.0/jquery.min.js
http://yandex.st/jquery/1.3.1/jquery.min.js
http://yandex.st/jquery/1.3.2/jquery.min.js
http://yandex.st/jquery/1.4.0/jquery.min.js
http://yandex.st/jquery/1.4.1/jquery.min.js
http://yandex.st/jquery/1.4.2/jquery.min.js

Non minified versions
http://yandex.st/jquery/1.2.6/jquery.js
http://yandex.st/jquery/1.3.0/jquery.js
http://yandex.st/jquery/1.3.1/jquery.js
http://yandex.st/jquery/1.3.2/jquery.js
http://yandex.st/jquery/1.4.0/jquery.js
http://yandex.st/jquery/1.4.1/jquery.js
http://yandex.st/jquery/1.4.2/jquery.js

jQuery UI links

http://yandex.st/jquery-ui/1.8.2/jquery-ui.min.js

Hosted versions
1.8.2, 1.8.1, 1.8.0, 1.7.3, 1.7.2, 1.7.1, 1.7.0, 1.6.0

jQuery UI modules can be downloaded seperately
http://yandex.st/jquery-ui/1.7.2/effects.blind.js
http://yandex.st/jquery-ui/1.8.0/jquery.effects.blind.min.js

Language files
http://yandex.st/jquery-ui/1.7.2/i18n/ui.datepicker-ru.js
http://yandex.st/jquery-ui/1.8.0/i18n/jquery.ui.datepicker-ru.min.js

jQuery UI CSS files (matches original directory names)
http://yandex.st/jquery-ui/1.8.0/themes/humanity/jquery.ui.all.min.css

jQuery.live() – event binding to AJAX loaded elements

jQuery.live() function was introduced in jQuery version 1.3. It makes it easy to dynamically bind events to DOM elements that have not yet been created. In other words, it helps you to easily attach events to AJAX loaded elements that match your criteria.

NOTE:
If for some reason you are using old versions of jQuery, prior to 1.3, you will need to use event delegation or another method as they are described in my previous post named “How to bind events to AJAX loaded elements in jQuery 1.2.x”.

So, how does .live() function works?

It uses event delegation technique to bind to the events that fire on your page. In other words, it binds an event to the DOM tree’s root and listens to all events. When an event is fired it checks it’s originator and checks if we have bound any events to that particular DOM element.

// Example usage of jQuery().live() function
$('.mySelector').live('click', function(event){
    // my click event handler
});

// As of jQuery 1.4.1 .live() can accept
// multiple events, just like .bind() does
$('input').live('focus blur', function(event){
    // fires on focus and blur
});

You can also pass in additional data to your events to overcome some issues caused by closure. This was introduced in jQuery 1.4. Also, it worth mentioning that data is passed when the binding is made. Keep this in mind when you pass in dynamic data.

$('.mySelector').live('click', {myVar: 'myVal'}, function(event){
    // my click event handler
});

NOTE:
Some events were not supported cross browser in jQuery 1.3. Events like submit were supported in Firefox only. This is resolved in jQuery 1.4. Other methods that were not supported cross browser in jQuery 1.3 include: focusin, focusout, mouseenter, mouseleave, etc.

NOTE:
.live() function also works with custom events.

jQuery.live() function performance

Because .live() uses event delegation and performs additional checks, it will always be slower then events attached to the DOM elements using .bind() function (this includes shorthands like: .click(), .submit(), etc.). However, you can improve your .live() function performance providing context (as of ver. 1.4).

// Using context for better performance
// Note that context is a DOM element, not jQuery
$('.mySelector', $('.myParent')[0]).live('click', function(event){
    // my faster click event
});

Unbinding events attached using .live() function

.unbind() function equivalent of .live() function is .die(). You can unbind ALL events attached using .live() function from an element by simply calling .die(). If you want to remove a specific event or a specific handler function of a specific event type, you can call .die('event', functionHandler).

// Remove ALL events attached using .live()
$('.mySelector').die();

// Remove myFunk() from click event
$('.mySelector').die('click', myFunk);

function myFunk(){
   alert("Clicked!");
}

If you have any questions or need any help, you can ask me on Facebook.

Host jQuery on Microsoft CDN servers

After Microsoft decided to ship and use jQuery library for its JavaScript needs in Visual Studio, hosting jQuery on Microsoft CDN servers is actually a logical and good decision. Yes, some of us might argue that Google already hosts jQuery, but Microsoft can not recommend to use its competitor’s services, can it?! :)

Anyway, intention of this post is not to discuss why Microsoft introduced its own jQuery hosted servers, bu to share links to Microsoft hosted jQuery library. Here we go:

jQuery 1.4.x
http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.js
http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js
http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1-vsdoc.js

jQuery 1.3.2
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.js
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.min.js
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2-vsdoc.js
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.min-vsdoc.js

Microsoft also host jQuery Validation and jQuery UI files.

Currently Microsoft AJAX CDN hosts only jQuery version 1.3.2, but they will add more releases in the future. To see a full list of the JavaScript libraries and their URLs that are already hosted on CDN cache go here: www.asp.net/ajax/cdn

Javascript for() loop vs jQuery .each() performance comparison

This post is an outcome of 15 minutes of free time and a question that I had yesterday. This question were:

  1. How fast jQuery’s .each() method is?
  2. How does it compare to javascript’s native for loop?

It is clear without any performance tests that native javascript for loop is faster, but I always used jQuery’s .each() utility with caution. It always felt like I will get a performance penalty for using it. So I tried to never use it.

So today, I wrote up a little javascript performance test and got my answers. Basically, I created an array and iterated through it using native for loop and jQuery’s .each() iterator. All I did was just an iteration and no array amendments or any other logic. I know it is very basic, but that’s exactly what I want to know. How fast they iterate!

Performance test code:

console.time('TestNative');
length = myArray.length;
for( i=0; i < length; i++){
  myArray[i];
}
console.timeEnd('TestNative');

console.time('TestjQuery');
jQuery.each(myArray, function(i, val) {
  val;
});
console.timeEnd('TestjQuery');

Performance test results:

JavaScript Native FOR loop

Array size    Time
==========    ======
10,000        7ms
100,000       62ms
1,000,000     613ms


jQuery .each() loop

Array size    Time
==========    ======
10,000        10ms
100,000       177ms
1,000,000     1100ms

As you can see native for loop is never over 1ms. That’s probably because we are not doing anything with our array and browser simply optimizes the code or maybe its that fast :)

Usually we don’t have more than 1000 items in our arrays and objects, that is why I guess it can be concluded that using .each() loop in our code will not cause any performance penalties.

Tip for jQuery & handheld device developers

This week’s usual “Friday short post” about using jQuery in handheld devices. If you are a developer who is using jQuery in applications that were developed for use in environments with small processing power such as handheld devices, mobile phones, PDA’s, etc. you will find this post useful.

Anyway, back to the topic. For whatever reasons you chose to use jQuery in your application (I would suggest using plain javascript for better performance) jQuery effects such as animation, hide and show, etc. most likely were probably one of the reasons. Unfortunately, jQuery effects are process intensive and in “slow” environments it is recommended to turn them off. Fortunately, jQuery provides you with such a method. It lets you disable all animations and effects by changing jQuery.fx.off setting to true.

// Dissable all effects
jQuery.fx.off = true;

// Shorthand
$.fx.off = true;

Now all your effects such as fadeIn(), fadeOut(), slideDown(), slideUp(), etc. will not be animated. They will simply be hidden and shown immediately (by changing CSS rules display:none; display:block;) to save CPU processing time.

NOTE:
By setting the jQuery.fx.off back to false you enable all animations and effects.

Convert javascript objects into arrays for better performance

jQuery Howto blog has many posts on your javascript  and jQuery code performance. If you have read the last performance post named “5 easy tips on how to improve code performance with huge data sets in jQuery” then you probably got an idea that it’s better to work with arrays for better javascript performance.

The only problem is that jQuery returns an object not an array when you select elements. Consider you have an object with lots of entries and you have to perform some manipulations that are available in javascript array such as reverse, sort, join, etc. Using built in methods is much faster then those you might write yourself. So the best thing would be converting your objects to arrays and jQuery provides utility method that does exactly this – jQuery.makeArray(obj).

// From jQuery Documentation
var arr = jQuery.makeArray(document.getElementsByTagName("div"));
arr.reverse(); // use an Array method on list of dom elements
$(arr).appendTo(document.body);

5 easy tips on how to improve code performance with huge data sets in jQuery

Sitting on jQuery's support mailing list I noticed that developers use jQuery with huge data sets and their code becomes very slow. Examples would be generating very long tables with a lot of rows using AJAX to get JSON data. Or iterating through a long (very long) list of data, etc.

So I compiled a list of 5 easy tips on how to improve your code performance while working with huge data sets in jQuery.

  1. Use JavaScript native for() loop instead of jQuery's $.each() helper function.

    Native browser functions are always faster then any other helper functions that were built to add an abstraction layer. In case you are looping through an object that you have received as JSON, I highly recommend you rewrite your JSON to contain an array rather than an object.

  2. Do NOT append an element to the DOM in your loop.

    This one is probably one of the most important tips that will significantly improve your code performance. It is so important that I will repeat myself. Do not append a new element to the DOM in your loop statement. Instead store it in a variable as text and append it to the DOM after your loop finishes like this:

    // DO NOT DO THIS 
    for (var i=0; i<=rows.length; i++)  
    { 
        $('#myTable').append('<tr><td>'+rows[i]+'</td></tr>'); 
    } 
    
    // INSTEAD DO THIS 
    var tmp = ''; 
    for (var i=0; i<=rows.length; i++)  
    { 
        tmp += '<tr><td>'+rows[i]+'</td></tr>'; 
    } 
    $('#myTable').append(tmp);

  3. If you have a lot of elements to be inserted into the DOM, surround them with a parent element for better performance.

    When you have a lot of elements to insert into the DOM tree it takes time to add them all. Somehow adding one element with 1000 children is faster than adding 1000 children separately. You can search this site for performance tests that prove it.
    So, to improve our previous example's performance let's cover <tr>'s with <tbody> tag like this:

    var tmp = '<tbody>';
    for (var i=0; i<=rows.length; i++)
    {
        tmp += '<tr><td>'+rows[i]+'</td></tr>';
    }
    tmp += '</tbody>';
    $('#myTable').append(tmp);

  4. Don't use string concatenation, instead use array's join() method for a very long strings.

    var tmp = [];
    tmp[0] = '<tbody>';
    for (var i=1; i<=rows.length; i++)
    {
        tmp[i] = '<tr><td>'+rows[i-1]+'</td></tr>';
    }
    tmp[tmp.length] = '</tbody>';
    $('#myTable').append(tmp.join(''));

  5. And the last but not least use setTimeout() function for your long list looping and concatenation functions.

    This will make sure that page does not freeze while it loops through the long list of data and lets users to work with your page meanwhile.

    It was well mentioned in comments that setTimeout() function should be used to split your code processing into little chunks so your browser does not freeze up like this:

    function myFunk(data){ 
         
        // do processing 
         
        if(!has_finished) 
            setTimeout("myFunk()", 100); 
    }

How to disable all jQuery animations at once

Yesterday I came across jQuery.fx.off setting in jQuery documentation. It disables all jQuery animations effective immediately when you set it's value to true.

Consider this code:

jQuery.fx.off = true;

$("input").click(function(){
  $("div").toggle("slow");
});

Your div will be showed/hidden immediately without animation. One of the reasons (as documentation mentions) to disable animations would be "slow" environments.

jQuery 1.2.6 and jQuery 1.3 class selector performance benchmark

Reading about the jQuery 1.3's new selector engine Sizzle and its speed improvements I thought I would do a performance comparison between jQuery 1.2.6 and jQuery 1.3. I was prepared for something good, but the test results blew my mind.

I had a page with one unordered list with 1000 items each with a class (class="1", class="2", etc).

Here is  are the tests and results:
console.time("testClass");
for(i=0;i<100;i++){
    $('.'+i);
}
console.timeEnd("testClass");
/**
* jQuery 1.2.6

1235 ms
1326 ms
1342 ms
=======
1301 ms

*/
/**
* jQuery 1.3

54 ms
52 ms
53 ms
=======
53 ms

*/

As you can see the new selector engine is freakishly fast :) Actually with this specific test it is 25 times fast. Taking into the consideration that class selection is one of the most used selectors, we can assume that our code will work considerably faster.

NOTE:
I have performed the same  tests with selection with id's. The result were exactly the same (9 ms). Taking into the consideration that both versions of jQuery use browser's built in getElementById() function for ID selections, there is not much one can do to beat that.

Pack and minimize your JavaScript code size

In pursue for my JavaScript code performance and some questions on jQuery mailing list I looked for and eventually came across some of the JavaScript code packers. Here is a list of custom JavaScript code compressors available for free.

  1. YUI Compressor (from Yahoo)
  2. JSMin (by Douglas Crockford)
  3. ShrinkSafe  (from Dojo library)
  4. Packer (by Dean Edwards)

According to general opinion of developers on the net (and jQuery official site) you should use Yahoo's YUI Compressor to compress your jQuery and JavaScript code.

Improving jQuery code performance

Following jQuery performance related articles here is another tip to boost your jQuery code performance. You should use ID selections whenever you can. Because jQuery uses browser's native getElementById() function which is much faster.

Now back to JavaScript code performance testing. I have an unordered list with 1000 items. First test will have list items with class attributes and the second list will have id attributes set to its items.

console.time('test');  
for (i = 0; i < 500; i++) {  
    $('.'+i);  
}  
console.timeEnd('test'); 
// ~8204ms 

console.time('test');  
for (i = 0; i < 500; i++) {  
    $('#'+i);  
}  
console.timeEnd('test'); 
// ~32ms

As you can see selecting with element's #id is much faster. In our case 256 times (8204/32).

Caching in jQuery

What is great about jQuery is its simplicity in selecting elements. We all use it here and there, basically everywhere. This simplicity comes with its drawbacks. jQuery traverses through all elements every time we use selectors. So to boost up your jQuery application you should always cache your selections to some variable (if you find yourself using the same selection more than once). In case you are not selecting an element more than once you should not cache your selection by assigning it to some variable.

Here is an example:
var cached = $('.someElement'); 
cached.addClass('cached-element');
Here are the performance tests:
console.time('test'); 
for (i = 0; i < 1000; i++) { 
    $('.the').text(i + ' '); 
} 
console.timeEnd('test'); 
// ~260ms 

console.time('test2'); 
var the = $('.the'); 
for (i = 0; i < 1000; i++) { 
    the.text(i + ' '); 
} 
console.timeEnd('test2'); 
// ~30ms

As you can see caching increased performance by nearly 10 times.

How to test JavaScript code performance

Sometimes after all day long coding your code becomes not so effective and your code (usually interface related) becomes slow. You have done so many changes and don't exactly know what slowing it down. In cases like this (and of course, plenty other cases) you can test your JavaScript code performance.  First of all, you need Firefox browser and Firebug web developers life saver plugin. I can not think of my web programming work without it.

Anyway, Firebug makes available console variable to your JavaScript page. Console can be used for logging or printing out debugging information to the Firebug console. Console also has one handy method for tracking time in milliseconds.

console.time('timerName');

// Your javascript code to test here 

console.timeEnd('timerName');

You can use this script to test your JavaScript code. timerName in the code can be any name for your timer. Don't forget to end your timer using the same name for timeEnd().

Google hosted jQuery

Formerly Google AJAX API, now Google hosted libraries is a content delivery network (CDN) for several popular JavaScript libraries. The CDN provides reliable, high-speed, high-availability and global access to files hosted on it.

UPDATE:
You can also use jQuery hosted by Microsoft CDN servers.

If you are using one of the libraries belowe, Google has you covered:

  • AngularJS
  • Chrome Frame
  • Dojo
  • Ext Core
  • jQuery & jQuery UI
  • MooTools
  • Prototype
  • script_aculo_us
  • SWFObject
  • Web Font Loader

As you can see, Google CDN also hosts jQuery (as well as jQuery UI). In this post we will concentrate on jQuery.

Google CDN hosts uncompressed as well as minimized jQuery files, supports gzip. The main advantage of using Google hosted jQuery is that if your visitors have already visited some site that loaded jQuery from Google servers, then it would already be on user's machine. So the browser would load it from its' cache.

Today, almost everyone is using Google hosted jQuery. So there is a huge chance that your visitors have it cached. By using Google CDN, you are reducing your page load times.

Here is how to load jQuery from Google servers:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>

At the time of writing, Google hosts the following versions of jQuery:

2.0.3, 2.0.2, 2.0.1, 2.0.0,
1.10.2, 1.10.1, 1.10.0,
1.9.1, 1.9.0,
1.8.3, 1.8.2, 1.8.1, 1.8.0,
1.7.2, 1.7.1, 1.7.0,
1.6.4, 1.6.3, 1.6.2, 1.6.1, 1.6.0,
1.5.2, 1.5.1, 1.5.0,
1.4.4, 1.4.3, 1.4.2, 1.4.1, 1.4.0,
1.3.2, 1.3.1, 1.3.0,
1.2.6, 1.2.3

You can see up to date versions of hosted jQuery versions on Google Developers page.

Legacy method: Loading jQuery using Google AJAX API

Up until jQuery version 1.7.2, Google had javascript library loader API. If your legacy project is already using it to load other libraries, here is how you can use it to load jQuery.

<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("jquery", "1.7.2");
  google.setOnLoadCallback(function() {
    // Your code goes here.
  });
</script>

Loading jQuery UI from Google CDN servers

Google CDN also hosts jQuery UI files. So if you are using jQuery UI you can also load it using these links and code:

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js" type="text/javascript"></script>

<!-- OR Legacy method -->

<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("jquery", "1.3.2");
  google.load("jqueryui", "1.7.2");
  google.setOnLoadCallback(function() {
    // Your code goes here.
  });
</script>

Currently Google hosts these versions of jQuery UI library:

1.10.3, 1.10.2, 1.10.1, 1.10.0,1.9.2, 1.9.1, 1.9.0,
1.8.24, 1.8.23, 1.8.22, 1.8.21, 1.8.20, 1.8.19, 1.8.18, 1.8.17, 1.8.16,
1.8.15, 1.8.14, 1.8.13, 1.8.12, 1.8.11, 1.8.10, 1.8.9, 1.8.8, 1.8.7, 1.8.6,
1.8.5, 1.8.4, 1.8.2, 1.8.1, 1.8.0, 1.7.3, 1.7.2, 1.7.1, 1.7.0, 1.6.0, 1.5.3, 1.5.2