Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 + Turbolinks: JS in the head or at the bottom of the body?

I'm used to sticking my JS at the bottom of my body element (as per HTML5Boilerplate), but since TurboLinks, which will be on by default in Rails 4, reloads the body (and title) on every request, would it make sense to put my JS in the head from now on? Are there any decent guides or best practices on this yet?

like image 1000
stephenmurdoch Avatar asked Sep 28 '12 14:09

stephenmurdoch


People also ask

How does Turbolinks work?

Turbolinks Overview It works by intercepting all link clicks that would navigate to a page within the app, and instead makes the request via AJAX, replacing the body with the received content. The primary speedup comes from not having to download or parse the CSS & JS files again.

What is Turbolinks load?

If you're a Rails developer, chances are that you know Turbolinks. Turbolinks is a flexible and lightweight JavaScript library aimed to make your navigation through webpages faster. Turbolinks improves webpage performance by substituting the common full-page loads for partial loads in multi-page applications.


1 Answers

If you're using Turbolinks 5, you can now put turbolinks at the bottom of your body (and follow web dev best practices for rendering a page). This also helps with SEO ever so slightly. Simply add your scripts to the bottom of your body and add

data-turbolinks-eval="false"

to your script tag. This will prevent turbolinks from evaluating after the initial page load. Here's how it is done with the javascript_include_tag:

<%= javascript_include_tag 'application', 'data-turbolinks-eval' => 'false'%>

Then just use

$(document).on('turbolinks:load', function() { // code to be executed when use changes pages });

like image 54
Will Avatar answered Sep 18 '22 14:09

Will