Read more

Speed up your websites: Put JavaScripts at bottom

Tobias Kraze
July 19, 2013Software engineer at makandra GmbH

We now recommend to load JavaScripts with a <script defer> tag in the <head>.

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.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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:

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

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

    to

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

    :javascript
      alert("Hello")
    

    to

    - at_bottom do
      :javascript
        alert("Hello")
    
Posted by Tobias Kraze to makandra dev (2013-07-19 16:21)