3

In my Rails app, every page includes all of the JavaScripts in assets.

Some custom scripts are for Ajax and some fancy stuff. which run unnecessarily from every page and are causing me unnecessary overload.

For example, the session page doesn't really need any JavaScript at all, still all scripts are included. How do I change this? I have Rails 3.2.2.

<script src="/assets/jquery-1.7.2.js?body=1" type="text/javascript"></script>
<script src="/assets/jquery.ui.core.js?body=1" type="text/javascript"></script>
<script src="/assets/jquery.ui.widget.js?body=1" type="text/javascript"></script>
<script src="/assets/jquery.ui.position.js?body=1" type="text/javascript"></script>
<script src="/assets/jquery.ui.autocomplete.js?body=1" type="text/javascript"></script>
<script src="/assets/special.js?body=1" type="text/javascript"></script>
2
  • 1
    If your web server is properly returning caching headers for your scripts, note that it doesn't hurt to have them 'loaded' for pages that don't need them. Indeed, most of my sites use a single minified JavaScript file included on every page of the site, and that JavaScript file conditionally executes code based on which page it is on. Commented May 18, 2012 at 16:43
  • We have published a gem that resolves this issue, check the blog post eng.wolox.com.ar/blog/2013/04/19/introducing-loadjs Commented Apr 25, 2013 at 18:19

2 Answers 2

8

I use content_for.

application.html.erb

<head>
  <%= yield :custom_js %>
</head>

your_page.html.erb

<% content_for :custom_js do %>
   <!-- your script includes go here -->
<% end %>
Sign up to request clarification or add additional context in comments.

2 Comments

Tried that. Seems like my pages are including all scripts in the asset folder, even though I took them out from application.js. all scripts are loaded.
Look for require_tree in the application.js, this is what is loading them.
2

Don't put the <script> elements in your layout, put them on the page(s) you need. Alternatively, have your layout conditionally include them based on logic set in your controller.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.