0

I have a Rails 3.2 application with a standard asset pipeline - that is, controller has its own Javascripts defined in separate CoffeeScript files.

I noticed today that in development mode (when all JS files are loaded individually on every page) they stop working after a certain point. I'm assuming this is because there's a mystery error somewhere in one of the files above it. The console shows two errors related to elements not being found on that page (to be expected, since they are from a different controller).

But, I looked at the production application and the same thing is happening. I am on the pages controller for the homepage, looked at the miniaturized JS file and found references to a completely separate controller. The same errors were also present saying that elements weren't found on that page. And again, the JS after that point all failed and aren't working.

I assumed that Rails only compiled that controllers JS? If this isn't the case, how do I go about making it that way so that certain JS only appears on certain pages?

Thanks in advance for any help!

Justin
  • 1,956
  • 3
  • 23
  • 34
  • This is the default behavior of the asset pipeline i believe, you can load them separately, see this answer http://stackoverflow.com/questions/602147/javascript-file-per-view-in-rails but you need to think about performance aswell, by having everything complied in one file you have one HTTP request as opposed to many and then this can be cached, enhancing performance – Richlewis Feb 15 '13 at 14:10
  • Justin, the errors that you are receiving on the page are breaking your JS (or the rest of the loading of js). Fix those errors and then see if you can reproduce the not working part – ilan berci Feb 15 '13 at 14:11
  • @Richlewis - I suppose it makes most sense to have them all in a single file, otherwise each page would require separate downloading of a different miniaturized file. But, how do you specify within jQuery/CoffeeScript then to only run certain functions on certain pages? My errors are the result of the user not being on the page and the selector's element missing... – Justin Feb 15 '13 at 14:22
  • @ilanberci - Yes, I know that's what's causing the problem and I know the errors (see above, about elements not being on the page). I was moreso wondering how to get around loading those JS files on pages where the elements don't exist. – Justin Feb 15 '13 at 14:24

1 Answers1

0

You could put the functions behind if statements, that way they would only fire if certain elements are on the page.

if $("#element-id")
  namedFunction = ->
    etc....
pizza247
  • 3,869
  • 7
  • 33
  • 47
  • Thanks, that did the trick, except it worked without the `> 0`, so just `if $('#element').length { }`. – Justin Feb 15 '13 at 20:26