开发者

How Jammit handle view specific JavaScript

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

Default config provided in documentation grabs all js 开发者_StackOverflow社区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é

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜