AntoineLev AntoineLev - 8 months ago 55
jQuery Question

Disabling turobolinks to serve page specific javascript

I you have a highly interactive event driven page in rails with Turbolinks.
Having different interactions on different pages, events like window.resize will trigger on pages where I don't really need it.

Is it worth to sacrifice navigation time by disabling Turbolinks to serve page specific javascript, or should I not care and just use if statement in Jquery to check if certain elements are present in the page using their ID.

What is the rails way of doing this?


It is not recommended to serve page specific assets such as javascript. This slows down the user experience since navigating to a new page triggers another asset download.

The whole point of the Rails Asset Pipeline is to gather your assets, minify them and concatenate them all into a single file that the browser downloads only once, the first time a user navigates to your page.

Yes, use jQuery to check if certain elements exist to run some behavior.

The way I've found useful is to not think about js behaviors as page specific but rather, widget specific. e.g. if there's a sortable table in the DOM then initialize the sortable table widget i.e. $(".sortable").sortable()

The above example uses the jQuery plugins pattern. Place your behavior/widget logic inside the jQuery plugin and it will only run when the selector finds elements e.g. $("#nonexistant").something(), something() will not be called. $("#definitelyExists").somethingElse(), somethingElse() will be called.

In the preceding examples, when an element is found and the function is called, the this of the function references the matched elements and you can run your behavior logic on them.