Efficient way to manage javascript/coffeescript code for Rails 5?

Viewed 534

I'm building a web application in Rails 5.0.2. I have following JS files for my project:

enter image description here

Moreover, I have similar pattern for each of my own JS files as given below:

$(function () {
    var init = function () {
        // my code, I want to run on specific page load i.e. /remarks
        $('form#cf_remarks_form').validate(validate_options);
    };
    init();
    document.addEventListener("turbolinks:load", function () {
        init();
    });
});

I have following reservations/question on using JS assets:

  1. Rails by default attaches (and as a result they run) all js files on all pages for same layout. Is it good to add only relevant js on specific resources/pages by using customized pattern or go with default?

  2. If all js combine and linked to every page, I need to be very specific/cautious while using jQuery selectors as selection $('div.custom input.no-search') for one page might run me crazy if I have a lot of code and qualifying tag in another page on which I don't want to run a method, mentioned selector is selecting.

  3. Rails 5 uses ajax loading for normal pages. If have a file company.js for page /company, it will be executed on first page say /home. When I'll go to /company, lines written in company.js will not execute again. So, I have to use turbolinks:load event listener and encapsulate every UI initializing and UI attached events in a method to be called at turbolinks:load as well as normal call. (As shown in code snippet)

So, I want to know what practice rails developers follow for js assets specially who are using Rails 5? It will be great help if your answer address my concerns given above.

1 Answers
Related