Skip to content

Instantly share code, notes, and snippets.

@kevinthompson
Created January 17, 2014 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinthompson/8483496 to your computer and use it in GitHub Desktop.
Save kevinthompson/8483496 to your computer and use it in GitHub Desktop.
Potential Solution for Page-Specific JavaScript
# ./app/assets/javascripts/app.js.coffee
@App ||= {}
# ./app/assets/javascripts/app/view.js.coffee
class @App.View
@where: (params = { controller: null, action: null }) ->
controller = @_parseClassName(params.controller)
action = @_parseClassName(params.action)
try
new App.View[controller][action]
catch error
new this
@_parseClassName: (text) ->
text = text.replace /\W/, '.'
text = text.replace /(?:\b|_)([a-z])/g, ($0, $1) -> $1.toUpperCase()
render: ->
console?.log "No view found."
# ./app/assets/javascripts/app/view/dashboard.js.coffee
class @App.View.Dashboard extends @App.View
# ./app/assets/javascripts/app/view/dashboard/show.js.coffee
class @App.View.Dashboard.Show extends @App.View
constructor: ->
console?.log 'View instantiated.'
render: ->
console?.log 'View loaded.'
# ./app/assets/javascripts/application.js.coffee
$ ->
@view = App.View.where
controller: $('body').data('controller')
action: $('body').data('action')
@view.render()
@chantastic
Copy link

I don't know enough about Rails to know if this is a terrible idea or not...

What if, in application.js you changed require_tree . to require_directory . so that it only compiles application level files. Then have the layout grab the controller specific JS:

= javascript_include_tag "{params[:controller]}"

Stupid?

@kevinthompson
Copy link
Author

That's not a stupid idea, no. It's a simpler solution and might be good enough for most applications. Ultimately there's a threshold. If every new page the user visits makes an additional HTTP request for that page's JS, then performance may suffer. If an additional page-specific js file is needed in only a few sections of the application, then it might be more beneficial to simplify the logic and load the additional files as you've suggested.

@chantastic
Copy link

Our js changes a lot. I wonder if, at the end of the day, the additional HTTP request wouldn't be more performant. As it stands now, a change to any JS file busts the cache on application.js and requires the user to re-download the entire application. In this example, only changed changed would be is re-downloaded and only when the user navigates to that controller.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment