Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include page specific javascript in rails 4

Doing a google search gives depreciated answers for older versions of rails or says to use turbolinks. I like the idea of the coffeescript files but don't want to write everything in coffeescript is there a way to have a item.coffee and item.js file so it reads both. I saw this in a rails cast but that video was pretty old and that approach doesn't seem to work now.

If the only way is to use turbolinks to add page specific js to a page how is that done?

like image 539
Rob Avatar asked Mar 15 '26 12:03

Rob


1 Answers

I know the answers to your questions; this might be verbose...


is there a way to have a item.coffee and item.js file so it reads both

Coffeescript is a pre-processor.

In as much the same way as SCSS/SASS, it runs through "coffeescript" code and translates into standardized JS. In short, coffeescript is not a "language" in itself, it's just pseudocode for standard JS.

This means that if you're using a coffeescript extension, you can still use standard JS with it:

#app/assets/javascripts/item.js.coffee
alert("hello"); #-> Js
alert "hello"   #-> Cs

... same functionality.

--

If the only way is to use turbolinks to add page specific js to a page how is that done

It's not the "only" way. It's no way at all:

Instead of letting the browser recompile the JavaScript and CSS between each page change, it [Turbolinks] keeps the current page instance alive and replaces only the body (or parts of) and the title in the head

Turbolinks replaces the <body> of your page if the assets remain the same (it speeds up page load by removing the need to re-initialize the assets each time).

Of course, this is null & void when dealing with different assets.

If you have a different set of assets (different layout etc), Turbolinks will reload as appropriate:

#app/views/layouts/application.html.erb
<%= stylesheet_link_tag :application, (:transactions if controller_name == "transactions") %>

In this case, Turbolinks refreshes the entire page, which will update your assets through the refresh.

like image 123
Richard Peck Avatar answered Mar 17 '26 03:03

Richard Peck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!