Rails 3: Accelerate Ajax applications

Source: Internet
Author: User

Bkjia.com May 18 Internet headlines] Over the past two weeks, I have been searching for methods that can further improve the UI performance. The main result is to return the correct HTTP status code, the browser cache function is optimized.

BKJIA recommended topics: Ruby On Rails development tutorial

Specifically, two status codes are returned:

◆ 200-"OK" is returned, indicating that the Browser Server can successfully respond to the request. The response contains the data in the HTTP load returned from the server.

◆ 304-"Not modified" is returned, indicating that the request has Not been modified. This indicates that the data in the request sent by the browser has Not changed. Therefore, data can be loaded from the cache. In this case, the response does not contain HTTP loads.

Since the "Not modified" message contains much less data (NO content, only headers), You 'd better return to the browser, of course, you must first make sure that data already exists in the browser cache.

In my applications, I found that the server returns a much larger 200-response than 304-response. This causes two problems:

◆ Have to transmit more data than needed

◆ The UI has to process more data

These two problems will slow down the application speed. Although it is a little slower, it is still noticeable on the UI side. Fortunately, you only need to make a few small changes to the Rails application to get the expected results.

1. Use stale in the GET method? Statement

 
 
  1. def show  
  2.   @list_item = @list.list_items.find( params[ :id ] )  
  3.   if stale?( :etag => @list_item, :last_modified => @list_item.updated_at.utc, :public => true )  
  4.     respond_with( @list_item )  
  5.   end  
  6. end  

Stale? The statement will send back an etag and a last_modified date through the response. If the next request is the same URL, the browser will send the etag and last_modified date to the server. Then stale? The method will analyze the two parameters. if the content is the same, 304 is returned. If the parameter values are different, a new content is returned, and 200 is returned.

Want to know more about stale? For details about the method usage, refer to the Rails API documentation and the Rails manual.

2. Make sure that the browser receives new data for each request.

After the above modification is complete, some interesting things happen. In a short period of time, the same Ajax behavior was triggered many times, while the browser did not send a request to the server, but all obtained data from the cache. Although it makes the UI much faster, it is not exactly what I want. My goal is to achieve optimal performance while ensuring that the screen displays correct and up-to-date data.

The browser's buffer behavior is affected by the flag status of three HTTP headers: cache-controll, pragma, and expires

To disable the browser cache function, you can send the following code:

 
 
  1. def set_cache_buster  
  2.     response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"  
  3.     response.headers["Pragma"] = "no-cache"  
  4.     response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"  
  5.   end 

However, what I want to do is:

 
 
  1. def set_must_revalidate  
  2.     response.headers["Cache-Control"] = "must-revalidate"  
  3.   end 

This allows the browser to check the newly added and updated data in each request. I added this method to my application_controller.rb and called it in the before_filter controller.

3. Use stale in the GET method of the returned set? (For example, index)

Above stale? The example is taken from the show method of the controller. This is a very common practice on the network. If you want to use this method to return a set, such as a typical controller index method, you need to find out whether the current set is the same as that in the previous request.

My ListKungFu website has a List of types, including many listitems. Each ListItem belongs to a List. In order to check whether a ListItem set has changed in list_items_controller, I added a timestamp named list. updated_at, which is updated every write operation.

In ListItem. rb:

 
 
  1. class ListItem < ActiveRecord::Base 
  2.   belongs_to :list  
  3.   after_save :update_list  
  4.   after_destroy :update_list  
  5.    
  6.   # [...]  
  7.    
  8.   def update_list  
  9.     self.list.updated_at = Time.now  
  10.     self.list.save  
  11.   end  
  12. end 

In this way, the index method of list_items_controller looks like this:

 
 
  1. def index  
  2.     @list_items = @list.list_items  
  3.    
  4.     if stale?( :last_modified => @list.updated_at )  
  5.       respond_with( @list_items )  
  6.     end  
  7.   end 

If the updated_at field is not used, I can add a version field to the List model, but it does not seem necessary. If this model is not suitable for your application, you need to find another method to check whether the set has been modified. For example, you can calculate the checksum of all objects in the next set.

Major improvements to Rails 3.0:

1. New Active Record query engine

Sample Code:

 
 
  1. users = User.where(:name => "david").limit(20)  
  2. users.where("age > 29")  
  3. # SELECT * FROM users  
  4. # WHERE name = "david" AND age > 29   
  5. # ORDER BY name  
  6. # LIMIT 20  
  7. users.order(:name).each { |user| puts user.name }  

2. New router for Action Controller

Sample Code:

 
 
  1. resources :people do  
  2.   resource :avatar  
  3.  
  4.   collection do  
  5.     get :winners, :losers  
  6.   end  
  7. end  
  8.  
  9. # /sd34fgh/rooms  
  10. scope ':token', :token => /\w{5,5}/ do  
  11.   resources :rooms  
  12. end  
  13.  
  14. # /descriptions  
  15. # /pl/descriptions  
  16. # /en/descriptions  
  17. scope '(:locale)', :locale => /en|pl/ do  
  18.   resources :descriptions  
  19.   root :to => 'projects#index'  
  20. end 

3. New Action Mailer

Sample Code:

 
 
  1. class Notifier < ActionMailer::Base 
  2.   default :from => 
  3.     "Highrise <system@#{APPLICATION_DOMAIN}>"   
  4.  
  5.   def new_project(digest, project, person)  
  6.     @digest, @project, @person = digest, project, person  
  7.  
  8.     attachments['digest.pdf'] = digest.to_pdf  
  9.     attachments['logo.jpg']   = File.read(project.logo_path)  
  10.  
  11.     mail(  
  12.       :subject => "Your digest for #{project.name}",  
  13.       :to => person.email_address_with_name  
  14.     ) do |format|  
  15.       format.text { render :text => "Something texty" }  
  16.       format.html { render :text => "Something <i>texty i>" }  
  17.     end  
  18.   end  
  19. end 

4. Manage dependencies with Bundler

5. XSS protection is enabled by default.

6. Question of farewell to character encoding

7. Active Model: Validations, callbacks, etc for all models

8. Official plug-in API

9. Internal Reconstruction

10. Agnosticism with jQuery, rSpec, and Data Mapper

11. Complete documentation

Rails is a complete framework for developing database-driven network applications. Rails is based on the MVC (Model-View-Controller) design mode. From Ajax applications in the view, access requests and feedback in the Controller, to database encapsulation models, Rails provides you with a pure Ruby development environment. When publishing a website, you only need a database and a network server.

  1. Programmer's alternative realm: the founder of Rails, driving Porsche, to participate in a career Competition
  2. Run Ruby on Rails on Nginx
  3. Explanation of Ruby on Rails's success tips
  4. Migrate Twitter from Rails to Java
  5. Develop high-quality Web applications based On Ruby On Rails

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.