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>
<html>
  <head>
    <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.

SEO Tip

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.

References

X-DNS-Prefetch-Control
SEO basics for Rails developers
Github Gist


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.