Search code examples
ruby-on-railsturbolinks

Assets are reloaded between pages with Turbolinks 5 and Rails 5


In my production environment, I noticed Turbolinks was not caching assets between pages. When I come on the first page of my application, my javascript bundle gets loaded, so as my CSS. When I then get to another page with a link, I can see in the chrome devtools, network tab, that they are reloaded (HTTP code 200).

application.html.erb

<html>
<head>
    <title>My title</title>
    <meta name="description" content="My description">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="index, follow">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>

    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <%= csrf_meta_tags %>
    <%= action_cable_meta_tag %>
</head>
<body class="<%= body_user_class %> <%= controller.controller_name %>">
  // Stuff
</body>
</html>

application.js

//= require turbolinks
//= require jquery
//= require jquery.slick
//= require jquery-ui/sortable
//= require rails-ujs
//= require_tree ./components

The fingerprint of the assets remains the same between the first and the second page, so I don't think the issue comes from there.

I can understand why my bootstrap asset is reloaded, as it is referenced as a classical resource without using rails. But why are my application's js and css reloaded?


Solution

  • In your application JavaScript bundle, you have the following:

    document.addEventListener("turbolinks:before-visit", function(e) {
      e.preventDefault(),
      window.location = e.data.url
    })
    

    This cancels the default Turbolinks behaviour. If you remove this event listener, it should work as expected.