Posts Tagged ‘jquery’

14
10/09
2

jQuery Weighs Less

Well, that may not be 100% accurate. Unobtrusive JavaScript is likely to weigh less in a Rails application, but that doesn’t get fan boys riled up enough.

In a standard Rails application, Prototype is included by default as the JavaScript library and several of the html helper methods used in the views will generate Prototype code for you. A great example of this is link_to_remote which generates a link that will make an AJAX request to the desired url.

This Rails view snippet was found in my forum app:

<%= link_to_remote "delete", :update => nil,
  :url => post_path(post), :method => :delete,
  :confirm => "Are you sure you want to delete this post?" %>

And it generates this html mixed with some very obtrusive JavaScript:

<a onclick="if (confirm('Are you sure you want to delete this post?')) {
    new Ajax.Request('/posts/1', {asynchronous:true, evalScripts:true,
      method:'delete', parameters:'authenticity_token=' +
      encodeURIComponent('abcde')
    });
  }; return false;" href="#">delete</a>

There is nothing really wrong with this code. It works fine and did the job while it was in production. The problem is this one link is found in every single post on a thread page. This means the giant link can be repeated on the page hundreds of times.

After I made the switch to unobtrusive jQuery, I wanted to see exactly what kind of a difference it made in page sizes. I looked at three different thread pages, one with 1 post, one with 94 posts, and one with 306. Here are the page sizes (in bytes) and they show a pretty remarkable difference.

# of Posts jQuery Page Size Prototype Page Size % Difference
1 5,450 6,568 20.5
94 103,671 129,641 25.1
306 270,736 350,170 29.3

The difference ended up being quite a bit bigger than I was expecting and really helps sell me on jQuery. Unobtrusive Prototype could no doubt have dropped the page size just as much, but I’ll be sticking with jQuery from now on.