문제

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

도움이 되었습니까?

해결책

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...

다른 팁

I'm digging this up to point out an alternative to jashkenas approach, which is to link behaviour just to specific tags.

$(function() {
  $('#my-view-object').someBehaviour();
}

So, what's the catch? The main difference is that JS code tends to be linked to certain objects, not pages. In case you reorganize your views, you will to have to change your JS too. The other problem is that JS needs to be at the bottom of the page to squeeze the most out of the browser. If you are putting script entries in your views, then most likely they will end up being all over the page's html markup and slowing the rendering.

BR, -- José

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top