• Home
  • New Entries
  • Popular Entries
  • Submit a Story
  • About

AJAX Google API to Minify Javascript using Ruby on Rails ...

How to optimizing JavaScript performance in Ruby on Rails. This will only focus on one aspect of JS performance optimization, namely, writing a build script to concatenate/minify the JS, and setting up Rails to easily toggle between the compressed and normal files.

How to optimizing JavaScript performance in Ruby on Rails. This will only focus on one aspect of JS performance optimization, namely, writing a build script to concatenate/minify the JS, and setting up Rails to easily toggle between the compressed and normal files. Also, if your site uses a JavaScript library, we will explore including it from Google is AJAX Libraries API.

The reason to do these optimizations are for client-side performance. Concatenating many files together into one is especially effective: 10 1-kilobyte files are much slower to download than a single 10k file. You might not think it makes much of a difference, but I estimate that removing 10 additional JS files, for instance, will shave 500-1000ms off latency. Plus, all of the time spent loading the JS will leave the page blank, if you put it in the head.

We will need to be able to easily toggle between fully commented code and minified code, both for code hosted by us and code from the Google AJAX Libraries API. Since Google offers both minified and normal versions of the code, this should be no problem.
Including JavaScript in Ruby on Rails

First of all, let is look at how JavaScript is included in Ruby on Rails, the javascript_include_tag method. The method quite simply takes any number of source URLs and returns an HTML script tag for each of the sources provided. For instance:

  javascript_include_tag("script1.js", "script2.js", "script3.js")

Result:

<script type="text/javascript" src="/javascripts/script1.js"></script> <script type="text/javascript" src="/javascripts/script2.js"></script> <script type="text/javascript" src="/javascripts/script3.js"></script>

There is a little bit of magic you can do which is to include all JavaScript files in the /public/javascripts folder automatically, as well as having them concatenated into a single file. It looks like this:

  javascript_include_tag :all, :cache => true # when ActionController::Base.perform_caching is true

The resulting code is:

<script type="text/javascript" src="/javascripts/all.js"></script>

If you don want them concatenated into a single file, e.g. for development purposes, you could do something like this:

# config/environments.rb:
DEBUG_JS = false;

# environments/development.rb:
DEBUG_JS = true;

# app/views/layouts/site.html.erb or wherever you include the JavaScript in your site:
<%=   javascript_include_tag(:all, :cache => true) if DEBUG_JS == false || ENV["RAILS_ENV"] != "development"
 javascript_include_tag(:all) if DEBUG_JS == true && ENV["RAILS_ENV"] == "development"
%>

I am not sure how to integrate JSMin, YUICompressor or any other minification into the cached file, though, so I will explore the options for manual building and inclusion next.

Something else to remember is that caching needs ActionController::Base.perform_caching to be true in order to work. This is the default in production, but not development, though of course you can override it in your environments/development.rb file. For more information, view the docs for the javascript_include_tag.
JavaScript Concatenation and Minification

Next, we will write a custom build script to generate a concatenated, minified version of our files. Ideally, Rails would automatically run it through a minifier, but I am not sure how to set that up. In the meantime, this is a working solution that is pretty straightforward and requires minimal effort. I wish I were more skilled at shell scripting (and I highly urge readers to contribute their own code), but I will show my implementation as an example regardless.

I am on a Windows machine and wrote it as a batch file (.bat), but you can easily do this on linux, just using pipe (the | character) instead of the two right-angle brackets (>>). Here goes:

java -jar yuicompressor-2.3.5.jar "script1.js" -o main.js
java -jar yuicompressor-2.3.5.jar "script2.js" >> main.js
java -jar yuicompressor-2.3.5.jar "script3.js" >> main.js
java -jar yuicompressor-2.3.5.jar "script4.js" >> main.js

Nothing too sophisticated, just a straightforward script that generates main.js using the YUICompressor. To use it, simply run the batch file in the same folder as the JavaScripts and yuicompressor-2.3.5.jar. It will output a main.js file. I chose to run it separately for each individual file so if there are any errors, you can see where they occurred. If you concatenate all of the files into one and then compress it, debugging is difficult as the line number which threw the error is unknown.

I chose to use YUICompressor over JSMin since it seems to have better error messaging, warnings, and be a bit more strict. One of my former colleagues did some tests that determined that JSMin was faster in terms of using less CPU than YUICompressor (and certainly for minifiers which use eval(), such as Dean Edwards packer). Unfortunately, I can remember the specifics of the test or which platforms it was on, so that data is pretty much worthless. In any case, I decided on YUICompressor but you can use JSMin or whichever minifier you prefer.

If you are going to use YUICompressor, you must have Java installed and included in your path. If it isn in your path, you can use the full path to Java, for instance, "C:Program FilesJavainjava.exe" -jar [filename] [options].

Using the Google AJAX Libraries



Depending on your opinion about Google is recent offer to host the world is JavaScript frameworks with its AJAX Libraries API, you may not find this suggestion too useful, but I think it is helpful, especially to those without access to their hosting provider is response header settings, to present here. Without going into too much detail, suffice it to say that besides the caching benefit of using Google is API, their servers are configured "correctly" for best performance (far future expires headers, Gzip, etc).

One thing, though, is that you will want to include a minified version of the JavaScript in production and a full version in development, to ease debugging. It is impossible to debug minified JavaScript (don even try), so we have to set a toggle like in the above example. Say your site is including jQuery. You may want to include a minified version on the live server but read the full code locally.
Toggling Minified Google JS

Here is how you can include minified jQuery in the production Ruby on Rails code while including the full jQuery library, comments and all, in development:

<%=  
javascript_include_tag("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js",
                                            :all, :cache => true) if DEBUG_JS == false || ENV["RAILS_ENV"] != "development"

 javascript_include_tag("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js",
                                          :all) if DEBUG_JS == true && ENV["RAILS_ENV"] == "development"
%>

<

Or, if you didn want to include everything in the JS folder, and wanted to granularly include only specific files, you might rewrite it like so:

<%= if DEBUG_JS == false || ENV["RAILS_ENV"] != "development"
   javascript_include_tag ("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js",
                                            "main.js)
    elsif DEBUG_JS == true && ENV["RAILS_ENV"] == "development"
    javascript_include_tag("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js",
                                            "script1.js",
                                            "script2.js",
                                            "script3.js",
                                            "script4.js")
 end %>

That is all there is to it! Just switch the DEBUG_JS flag when you want to test in development mode with/without compression, and don worry about when it is in production since it will always serve up the minified, concatenated JavaScript. The logic ensures that you won accidentally start serving up the separate files in production, while giving you the flexibility to store your JavaScript in as many files as you like without negative consequences on the front end, as well as reading fully-commented code./p>

source: thetruetribe

 View Full Story.
Posted at 11:28:34 am | Permalink | Posted in Google  Javascript  Ruby  

Related Stuff

  • MooV: Using cutting edge Video phones and Software Video Phones - coupling all that with VoIP and empowering the disabled.

  • Moo Telecom: VoIP communications made easy - Ring anyway with the fun and ease of using a normal phone

  • TagR:Mobile Social Network with Real Time Locations Based services, and Ambience Intelligence, VoiP, IM, Skype, Googletalk, Mapping, Flickr, Events, Calendaring, Scheduling, SecondLife Support

  • ClearSMS : ClearSMS is a Web-based application that lets you send bulk SMS messages to your customers, contacts, or just about anyone.

  • Jajah:jah is a VoIP (Voice over IP) provider, founded by Austrians Roman Scharf and Daniel Mattes in 2005[1]. The Jajah headquarters are located in Mountain View, CA, USA, and Luxembourg. Jajah maintains a development centre in Israel.

  • Skype: It’s free to download and free to call other people on Skype. Skype the number one voice over ip software

  • PrivatePhone: a free local phone number with voicemail and messages you can check online or from any phone.

Be the first ... |Add your comment.

Your Comment ...

  Name (required)

  Email (required, hidden)

  Website


Top Stuff

e-messenger

MessengerFX

eBuddy

ILoveIM

AIM Express

Top 20 Ruby CMS


Our Partners

Facebook Applications

Ajax Projects

Web 2.0 Sites

Webloglines

Human Development Handbook

Software Development Company

Ajaxlines

Stock Exchange Chat


About Ajaxlines

Ajaxlines is a project focused on providing its audience with a database of most of Ajax related articles, resources, tutorials and services from around the world.

Its purpose is to showcase the power of Ajax and to act as a portal to the Ajax development community.


Search


Topics

  • .Net (114)
  • Articles (87)
  • Bookmarking (35)
  • Calendar (19)
  • Chat (40)
  • ColdFusion (3)
  • CSS (45)
  • Email (23)
  • Facebook (31)
  • Flash (16)
  • Games (6)
  • Google (29)
  • Html (14)
  • Image (11)
  • International Calls & VOIP (7)
  • Java (36)
  • Javascript (179)
  • JSON (21)
  • Perl (2)
  • PHP (91)
  • Presentation (19)
  • Python (3)
  • Resources (2)
  • RSS (1)
  • Ruby (11)
  • Storage (4)
  • Toolkits (90)
  • Tutorials (201)
  • UI (12)
  • Utilities (171)
  • Web2.0 (15)
  • XmlHttpRequest (22)
  • YUI (4)

© 2006 www.ajaxlines.com. All Rights Reserved. Powered by IRange