Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails 4: How to include Javascript files in Rails web application?

I am building a Rails 4 web application and I want to include some .js files into my application. Is it possible to directly add JavaScript file to my Rails ..app/assets/javascripts folder and add reference in application.js like this?

//= customejsfile.js  

Is this the right way? If yes, is it possible for me to follow the same steps in adding jQuery and Bootstrap library?

Any help is appreciated.

like image 689
Cyber Avatar asked Mar 10 '14 10:03

Cyber


People also ask

Where do I put JavaScript code in Rails?

The directory structure for JavaScript has changed to the app/javascript/packs/ folder. In that folder you will find the application. js file, which is just like the application.

How do I add JavaScript to my ERB?

you can create a custom js file in /assets/javascripts folder and write all your js code and it will load in your page also.

How do you include a JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.


1 Answers

The right way to include your files is:

//= require customejsfile 

in your application.js file. What's more, by default you have

//= require_tree . 

which requires all js files from assets/javascript path, so you don't have to type it on your own (and you shouldn't, or you'll have your file included twice). JQuery library is included by default (and it comes from jQuery gem). If you want Bootstrap, then you can do it this way or use one of existing gems, like bootstrap-generators or twitter-bootstrap-rails.

like image 199
Marek Lipka Avatar answered Sep 21 '22 23:09

Marek Lipka