Speeding up Page Load in Rails Applications

Step 1

Move javascript to the bottom of the document.

<%= javascript_include_tag "application", "data-turbolinks-track" => true, async: Rails.env.production? %>
<%= yield :third_party_js %>

<script type="text/javascript" src="https://js.stripe.com/v2/"></script>

This code is just above the body close tag.

Step 2

Add dns-prefetch tag to CDN and Google Analytics links

<link rel="dns-prefetch" href="//cdn.mydomain.com">
<link rel="dns-prefetch" href="http://www.google-analytics.com">

For Rails applications, you can provide the asset host in layout file:

<!DOCTYPE html>
    <title> <%= yield(:title) %> </title>
      <% if ActionController::Base.asset_host %>
        <link rel="dns-prefetch" href="<%= ActionController::Base.asset_host %>" />
      <% end %>
      <link rel="dns-prefetch" href="http://www.google-analytics.com">  

The ActionController::Base.asset_host will be nil in development. We don't need it in development. In production.rb it is initialized:

config.action_controller.asset_host = '//cdn.rubyplus.com'

Step 3

Move CSS to the top of the document.

<title> <%= yield(:title) %> </title>
  <% if ActionController::Base.asset_host %>
    <link rel="dns-prefetch" href="//<%= ActionController::Base.asset_host %>" />
  <% end %>

  <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>

Just below the dns-prefetch we have the CSS stylesheet tag.


Use canonical tags:

<% if yield(:canonical_link).present? %>
    <link rel="canonical" href="<%= yield(:canonical_link) %>" >
<% end %>

will result in:

<link rel="canonical" href="https://rubyplus.com/articles/4991-Rails-Serialization-Basics" >

in the article show page.


SEO basics for Rails developers
Github Gist

Related Articles

Software Compatibility Best Practices

I spoke to some of the most talented and experienced software developers. I have created a guide that is filled with valuable insights and actionable ideas to boost developer productivity.

You will gain a better understanding of what's working well for other developers and how they address the software compatibility problems.

Get the Guide Now