Nathan Tornquist
Nathan Tornquist

Reputation: 6609

Rails - Incorrect Assets Loading

Occasionally I'll click a link in my application, and the *.css and *.js files that are loaded are referring to the wrong controller. If I refresh the page, this is immediately fixed, but I do not want to tell my users that the occasional page refresh may be required.

This is where the content is loaded in my application layout:

= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true
= stylesheet_link_tag params[:controller]
= javascript_include_tag 'application', 'data-turbolinks-track' => true
= javascript_include_tag params[:controller]

And where the assets are loaded in my assets.rb initilizer

Rails.application.config.assets.paths << Rails.root.join('vendor', 'assets', 'flash')

%w( comments contact_types ensembles favorite_instruments fields gds gigs instuments
rank_members recruit_statuses scores seasons section_notes sections static students
announcements ).each do |controller|
    Rails.application.config.assets.precompile += ["#{controller}.js", "#{controller}.css"]
end

It's strange to me that sometimes it work work and other times, it would not. I assume that I have a gem issue with some of the page loading stuff. I am using turbolinks, spring, and quiet_assets. I don't think any of the other gems touch assets.

Upvotes: 0

Views: 161

Answers (1)

user229044
user229044

Reputation: 239311

TurboLinks intercepts requests and fetches only the body of the document, "seamlessly" substituting it into the DOM. It doesn't touch <head>, so your JavaScript includes are not changing until you fully reload the page and fetch a new document with the appropriate <head>.

TurboLinks (and Rails) assume you're going to have a single bundle of JavaScript, not many small conditionally included JavaScripts. You're going to have to either go the Rails-way, and stop using many small manifests, or turn off TurboLinks.

Upvotes: 2

Related Questions