javascriptruby-on-railsrubyjammit

How Jammit handle view specific JavaScript


I'm trying to adopt Jammit in my Rails application.

Default config provided in documentation grabs all js files including view specific javascript:

embed_assets: on

javascripts:
  workspace:
    - public/javascripts/vendor/jquery.js
    - public/javascripts/lib/*.js
    - public/javascripts/views/**/*.js
    - app/views/workspace/*.jst

stylesheets:
  common:
    - public/stylesheets/reset.css
    - public/stylesheets/widgets/*.css
  workspace:
    - public/stylesheets/pages/workspace.css
  empty:
    - public/stylesheets/pages/empty.css

Let's consider a case when view specific javascript should be executed only on certain view:

$(function(){
  alert("View specific message here!");
}

How can I avoid such effect?

Regards, Alexey Zakharov


Solution

  • My preference is to wrap up that "view-specific-javascript" in a function. And then call that function depending on the page you actually load. In this way, all of your JavaScripts can be cached by browsers as a single file, and you can execute the portions of the JS that you need.

    So I'd add a <script> tag to the particular html.erb template that calls your view-specific function on page load.

    Hope that helps...