Created
January 17, 2014 23:18
-
-
Save kevinthompson/8483496 to your computer and use it in GitHub Desktop.
Potential Solution for Page-Specific JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ./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() |
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
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.