What is the correct way to use page-specific JavaScript in Rails 6 (with turbolinks enabled)?
The articles I have found seem to suggest just putting everything in application.js - but this seems messy as it affects every page (and you also need to check the element you want to manipulate exists every time, then add an eventlistener or do nothing at all if it doesn't exist).
Another suggests adding your own folder, putting your custom JS in there and then requiring it from application.js (in effect, the same as above - it's just slightly more clean to look at but everything is still loaded for every page).
What I'd like to achieve is have my JavaScript split and only include it when needed. However, if using 'javascript_pack_tag' in a view to pull it in, this causes turbolinks to get quite upset and keep adding the event listeners, over and over. If you put 'javascript_pack_tag' in the page head, this then invalidates the cache and stops turbolinks from working.
In an ideal world;
- The JavaScript would be in it's own custom location
- It would be required only for the views that needed it
- It would work with turbolinks