2

In some of our Rails views, we have javascript functions that load certain data asynchronously to populate the page. Our application.js file loads all javascript in the assets/javascripts folder.

Here is a bit that's in one of our haml views:

:javascript
  $(function() {
    fetch_all_facebook_invitees();
  });

If we put the fetch_all_facebook_invitees function definition in a coffeescript file, it's loaded on every page because they're included in all pages of the application:

//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require_tree .

What's the best practice to loading javascript for a page? Only doing it selectively and not load the entire tree?

1

1 Answer 1

5

You could solve this by having "partial" coffee files that you render inline.

../assets/javascripts/inline/facebook_invites.js.coffee

Make sure all events inside the file is fired when the DOM is loaded

$ ->
  # do Facebook stuff

facebook.haml:

= javascript_include_tag "inline/facebook_invites"


Then there's also the approach that I use to make controller/view specific Coffee files:

application.html.haml:

%body{ :data => { :controller => params[:controller], :action => params[:action]} }

application.js.coffee:

$(document).ready ->
  load_javascript($("body").data('controller'),$("body").data('action'))

load_javascript = (controller,action) ->
  $.event.trigger "#{controller}.load"
  $.event.trigger "#{action}_#{controller}.load"

facebook.js.coffee

$(document).bind 'edit_facebook.load', (e,obj) =>
  # fire on edit facebook controller action

$(document).bind 'show_facebook.load', (e,obj) =>
  # fire on show facebook controller action

$(document).bind 'facebook.load', (e,obj) =>
  # fire on all facebook controller actions
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.