Posted about 6 years ago. Visible to the public. Repeats.

Speed up your websites: Put JavaScripts at bottom

For websites that don't do JavaScript rendering on the client, it's best practice to put script tags at the bottom of the HTML. This way, the page can start to render before scripts have been loaded and run.

The caveat is that you also have to move all other script tags from your views to the bottom of the page. This can be done with helpers.

How to implement

  1. Add the attached javascript_helper to your app.
  2. Move your javascript_include_tags out of <head> to the end of the <body> tag, and add one extra line, like this:

    Copy
    <body> Your content... <%= javascript_include_tag "application" ... %> <%= include_javascripts_at_bottom %> </body>
  3. In your ERB views change

    Copy
    <%= javascript_tag do %> alert("Hello"); <% end %>

    to

    Copy
    <% javascript_at_bottom do %> alert("Hello"); <% end %>
  4. In your Haml views change

    Copy
    :javascript alert("Hello")

    to

    Copy
    - at_bottom do :javascript alert("Hello")

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Tobias Kraze
Last edit:
about 4 years ago
by Arne Hartherz
Attachments:
javascript_helper.rb
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Tobias Kraze to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more