Skip to content

Improve perceived performance of your rails application with minimum effort

License

Notifications You must be signed in to change notification settings

antulik/pagelet_rails

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

70 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PageletRails

GitHub license Gem Version Build Status Code Climate Test Coverage

PageletRails is the addon for Rails which allows you to build components. Achieve amazing performance and reusability by slicing your webpages into components. PageletRails is built on top of Rails and uses it as much as possible. The main philosophy: Do not reinvent the wheel, build on shoulders of giants.

Why?

  • Do you have pages with a lot of information?
  • The pages where you need to get data from 5 or 10 different sources?
  • What if one of them is slow?
  • Does this mean your users have to wait?

Don't make your users wait for page to load.

View Demo Project

Example

For example let's take facebook user home page. It has A LOT of data, but it loads very quickly. How? The answer is perceived performance. It's not about in how many milliseconds you can serve request, but how fast it feels to the user.

The page body is served instantly and all the data is loaded after. Even for facebook it takes multiple seconds to fully load the page. But it feels instant, that it's all about.

Who is doing that?

Originally I saw such solution implemented at Facebook and Linkedin. Each page consists of small blocks, where each is responsible for it's own functionality and does not depend on the page where it's included. You can read more on that below.

What is Pagelet?

You can break a web page into number of sections, where each one is responsible for its own functionality. Pagelet is the name for each section. It is a part of the page which has it's own route, controller and view.

The closest alternative in ruby is cells gem. After using it for long time I've faced many limitations of its approach. Cells has a custom Rails-like syntax but not quite. That is frustrating as you have to learn and remember those differences. The second issue, and the biggest, cells are internal only and not designed to be routable. This stops many great possibilities for improving perceived performance, as request has to wait for all cells to render.

Usage

Installation

Add this line to your application's Gemfile:

gem 'pagelet_rails'

Or install it yourself as:

$ gem install pagelet_rails

Setup

Include small javascript extension pagelet_rails:

// file app/assets/javascripts/application.js

//= require jquery
//= require jquery_ujs
// ...
//= require pagelet_rails

Structure

app
├── pagelets
│   ├── current_time
│   │   ├── current_time_controller.rb
│   │   ├── views
│   │   │   ├── show.erb

Example Usage

# app/pagelets/current_time/current_time_controller.rb
class CurrentTime::CurrentTimeController < ApplicationController
  include PageletRails::Concerns::Controller

  # add pagelets_current_time_path route
  # which gives "/pagelets/current_time" url route
  pagelet_resource only: [:show]

  def show
  end
end
<!-- Please note view path -->
<!-- app/pagelets/current_time/views/show.erb -->
<div class="panel-heading">Current time</div>

<div class="panel-body">
  <p><%= Time.now %></p>
  <p>
    <%= link_to 'Refresh', pagelets_current_time_path, remote: true %>
  </p>
</div>

And now use it anywhere in your view

<!-- app/views/dashboard/show.erb -->
<%= pagelet :pagelets_current_time %>

Documentation

Pagelet view helper

pagelet helper allows you to render pagelets in views. Name of pagelet is its path.

For example pagelet with route pagelets_current_time_path will have pagelets_current_time name.

remote

Example

<%= pagelet :pagelets_current_time, remote: true %>

Options for remote:

  • true, :ajax - always render pagelet through ajax
  • :turbolinks - same as :ajax but inline for turbolinks page visit
  • false or missing - render inline
  • :stream - (aka BigPipe) render placeholder and render full version at the end of html. See streaming for more info.
  • :ssi - render through server side includes

params

Example

<%= pagelet :pagelets_current_time, params: { id: 123 } %>

params are the parameters to pass to pagelet path. Same as pagelets_current_time_path(id: 123)

html

<%= pagelet :pagelets_current_time, html: { class: 'panel' } %>

You can specify html attributes to pagelet with html option

placeholder

Configuration for placeholder before pagelet is loaded.

<%= pagelet :pagelets_current_time, placeholder: { text: 'Loading...', height: 300 } %>

or use your own placeholder template

 <%= pagelet :pagelets_current_time, placeholder: { view: 'path_to_template' } %>

other

You can pass any other data and it will be available in pagelet_options

<%= pagelet :pagelets_current_time, title: 'Hello' %>
# ...
  def show
    @title = pagelet_options.title
  end
#...

Pagelet options

pagelet_options is similar to params object, but for private data and config. Options can be global for all actions or specific actions only.

class CurrentTime::CurrentTimeController < ::ApplicationController
  include PageletRails::Concerns::Controller

  # Set default option for all actions
  pagelet_options remote: true

  # set option for :show and :edit actions only
  pagelet_options :show, :edit, remote: :turbolinks

  def show
  end

  def new
  end

  def edit
  end

end
<%= pagelet :new_pagelets_current_time %><!-- defaults to remote: true -->
<%= pagelet :pagelets_current_time %> <!-- defaults to remote: turbolinks -->

<%= pagelet :pagelets_current_time, remote: false %> <!-- force remote: false -->

Inline routes

Because pagelets are small you will have many of them. In order to keep them under control pagelet_rails provides helpers.

You can inline routes inside you controller.

class CurrentTime::CurrentTimeController < ::ApplicationController
  include PageletRails::Concerns::Controller

  pagelet_resource only: [:show]
  # same as in config/routes.rb:
  #
  # resource :current_time, only: [:show]
  #

  pagelet_resources
  # same as in config/routes.rb:
  #
  # resources :current_time
  #

  pagelet_routes do
    # this is the same context as in config/routes.rb:
    get 'show_me_time' => 'current_time/current_time#show'
  end

end

Pagelet cache

Cache of pagelet rails is built on top of actionpack-action_caching gem.

Simple example

# app/pagelets/current_time/current_time_controller.rb
class CurrentTime::CurrentTimeController < ::ApplicationController
  include PageletRails::Concerns::Controller

  pagelet_options expires_in: 10.minutes

  def show
  end

end

cache_path

Is a hash of additional parameters for cache key.

  • Hash - static hash
  • Proc - dynamic params, it must return hash. Eg. Proc.new { params.permit(:sort_by) }
  • Lambda - same as Proc but accepts controller as first argument
  • String - any custom identifier

expires_in

Set the cache expiry. For example expires_in: 1.hour.

Warning: if expires_in is missing, it will be cached indefinitely.

cache

This is toggle to enable caching without specifying options. cache_defaults options will be used (see below).

If any of cache_path, expires_in and cache is present then cache will be enabled.

cache_defaults

You can set default options for caching.

class PageletController < ::ApplicationController
  include PageletRails::Concerns::Controller

  pagelet_options cache_defaults: {
    expires_in: 5.minutes,
    cache_path: Proc.new {
      { user_id: current_user.id }
    }
  }
end

In the example above cache will be scoped per user_id and for 5 minutes unless it is overwritten in pagelet itself.

Advanced functionality

Partial update

<!-- app/pagelets/current_time/views/show.erb -->
<div class="panel-heading">Current time</div>

<div class="panel-body">
  <p><%= Time.now %></p>
  <p>
    <%= link_to 'Refresh', pagelets_current_time_path, remote: true %>
  </p>
</div>

Please note remote: true option for link_to.

This is default Rails functionality with small addition. If that link is inside pagelet, than controller response will be replaced in that pagelet.

# app/pagelets/current_time/current_time_controller.rb
class CurrentTime::CurrentTimeController < ::ApplicationController
  include PageletRails::Concerns::Controller

  pagelet_resource only: [:show]

  def show
  end

end

This will partially update the page and replace only that pagelet.

Streaming

This is the most efficient way to deliver data with minimum delays. The placeholder will be rendered first and the full version will be delivered at the end of page and replaced with Javascript code. Everything is delivered in the same request.

This mode requires rendering of templates with streaming mode enabled.

Warning: Session and Cookies are currently not supported in streaming mode.

  #...
  def show
    render :show, stream: true
  end
  #...

In you layout add pagelet_stream right before </body> tag.

<!-- app/views/layouts/application.erb -->

<body>
<%= yield %>

<% pagelet_stream %>
</body>

Usage:

<%= pagelet :pagelets_current_time, remote: :stream %>

Warning!!! You also should have webserver compatible for streaming like puma, passenger or unicorn (requires special config).

Warning!!! you need to have multiple threads/processes configured in the web server. This is required so the page could fetch assets while content is streaming.

Finally if everything is done right you should see significant rendering speed improvements especially on old browsers, slow network or with cold cache.

Super smart caching

Probably one of the coolest functionality of pagelet_rails is "super smart caching". It allows you to render pagelets through ajax and cache them, but if page is reloaded the pagelet is rendered instantly from cache.

So on the first page load user sees "Loading..." blocks, but after the content is instant.

The best thing, it's enabled by default if pagelet has caching enabled and is rendering through ajax request.

Ajax Batching

Only relevant for remote: true and remote: :turbolinks when request is loaded through ajax. Loading each pagelet with a separate request is inefficient if you need to do make many requests. That's why you need to group multiple requests into one. By default all ajax requests are grouped into single request. But you can have full control of it. You can specify how to group requests with ajax_group option.

<%= pagelet :pagelets_current_time, remote: true, ajax_group: 'main' %>
<%= pagelet :pagelets_current_time, remote: true, ajax_group: 'leftpanel' %>

There will be one request per group. Missing value is considered a separate group as well.

Todo

  • assets support with webpacker in rails 5.1
  • session (and CSRF) support in streaming mode
  • delay load of not visible pagelets (aka. below the fold)
    • do not load pagelets which are not visible to the user until user scrolls down. For example like Youtube comments.
  • high test coverage
  • update actionpack-action_caching gem to support rails 5

Links

License

The gem is available as open source under the terms of the MIT License.

About

Improve perceived performance of your rails application with minimum effort

Resources

License

Stars

Watchers

Forks

Packages

No packages published