chris
chris

Reputation: 36937

rails including javascript or files only on certain pages

Ok Im new to rails in general and these default loaders and cache loaders an all that stuff they make some sense to me. But my question is. If I want to include a certain JS file or 2 or specific script on a particular page how would I do that.

with rails I have app/views/layouts/application.html.erb in this file I gather is the base template for my site/service, and in there I would put all the moving parts. However I have an occasional need where I only need a javascript file loaded on a particular page. But it needs to be called after the jquery file so jquery is loaded into memory prior to the file I want loaded. So Im not exactly sure how I would approach that. Cause in the layout I have the javascript loader line whatever it is exactly I dont remember but its :default none the less which means jquery and applications will load out by default from what the API tells me.

Which does bring me to another question the guy who initially set up the rails server we have added a file to the defaults I would like to mimic that but don't know how with that either.

Upvotes: 1

Views: 4644

Answers (3)

Yuri Malov
Yuri Malov

Reputation: 1247


May be used for this:

<head>
<title>My blog</title>
<%= yield(:head) -%>
</head>

And send it there from a view:

<%- content_for(:head) do -%>
<%= javascript_include_tag :defaults -%>
<%- end -%>

It's good work!

Upvotes: -1

deviousdodo
deviousdodo

Reputation: 9172

The simplest way would be to just include the script file in the view where you need it. jQuery will have already been loaded in the layout. Alternatively, you can use content_for, as ctcherry mentions. You can find a more detailed explanation here: Javascript Include Tag Best Practice in a Rails Application

Also, regarding you last question, I'm not sure I understand it correctly, but you can add more options to the javascript_include_tag separated by a comma:

javascript_include_tag :defaults, "my_other_file", "etc"

Upvotes: 3

Chris Cherry
Chris Cherry

Reputation: 28554

content_for might help you, look at the example that includes the piece of code: <%= yield :script %>

Alternatively, think about ways to allow the JS code to detect if it is begin executed on the correct page (maybe a class or id set on the body tag), and only execute if that condition is met. Then you can serve your entire javascript collection compressed and minified to the user's browser on the first page load, increasing site performance.

Upvotes: 3

Related Questions