Search code examples
ruby-on-railsasset-pipelineturbolinks

Turbolinks and Controller-specific assets


I've modified application.html.erb to use controller specific assets:

application.html.erb:

<!DOCTYPE html>
<html>
<head>
  <title>My Application</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= stylesheet_link_tag params[:controller], 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag params[:controller], 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
<body>
... other html template ...

The problem is that, I have turbolinks installed. When I navigate through the same controller, turbolinks works. But when I switch to another controller, the turbolinks will perform a full reload. Is there any way to fix this?


Solution

  • Turbolinks

    Turbolinks takes the <body> of your HTML page, and changes it with Ajax, leaving the <head> area intact.

    This only works if your <head> will remain the same - otherwise how can it be kept constant? So in the sense of changing your controller page / assets, you're going to have to go through a full page update without Turbolinks (at least if you use Turbolinks without hacking it)

    I would recommend the fix for this would be to alter your controller-specific asset structure, specifically to make as few changes to the <head> area as possible.

    --

    Turbolinks Tracking

    Upon reading the Turbolinks documentation, you may be able to benefit from removing the turbolinks-data-track option from your controller-specific assets:

    <%= javascript_include_tag controller_name, 'data-turbolinks-track' => false %>
    

    You can track certain assets, like application.js and application.css, that you want to ensure are always of the latest version inside a Turbolinks session. This is done by marking those asset links with data-turbolinks-track, like so:

    <link href="/assets/application-9bd64a86adb3cd9ab3b16e9dca67a33a.css" rel="stylesheet" type="text/css" data-turbolinks-track>

    If those assets change URLs (embed an md5 stamp to ensure this), the page will do a full reload instead of going through Turbolinks. This ensures that all Turbolinks sessions will always be running off your latest JavaScript and CSS.

    --

    controller_name

    Something you'll benefit from is using the controller_name helper (in place of params[:controller]):

    <%= javascript_include_tag 'application', controller_name, 'data-turbolinks-track' => true %>