am-rails
am-rails

Reputation: 1473

Javascript not working on Production Rails page due to JS library error?

I have some simple javascript to hide and show blocks of text on my webpage which used to work fine. I recently placed a new javascript library in assets/javascripts to create other visual effects on my site. It works fine, but now my simple javascript no longer works online, though it still works locally. The Chrome console displays an error message from the library ("Uncaught ReferenceError: Raphael is not defined").

Could this be preventing the rest of my javascript from working on the production server but not on my local development server? How do I prevent the library in assets from loading on other pages so it doesn't break things all over?

Upvotes: 0

Views: 600

Answers (1)

PaReeOhNos
PaReeOhNos

Reputation: 4398

Yeah that could break the rest of your code. When you run rails in production, if you've used sprokets and required everything into application.js then it is all processed into a single file. If at any point in that file some javascript code fails, it will then break the rest of the file (which is pretty annoying)

You can conditionally include the raphael library which I assume you're already doing hence the error, but in your javascript code, you can also check to see if it is defined. What I'd do is around the code which makes use of Raphael, put something like :

if (typeof Raphael !== "undefined") {
    ... Raphael code goes here...
}

This way, if the library isn't loaded, it doesn't matter and your code won't break, and if it is loaded, then your Raphael specific code will run as normal :)

More info

I'd move the Raphael library into the vendor directory as well. It makes more sense, as this is specifically for assets that you haven't added/created yourself.

The reason rails is loading up Raphael automatically right now is most likely due to the default configuration of application.js. By default, rails sets this up with

//= require_tree .

This will include ALL JS files within the assets directory which is alright, but if you want to conditionally include files it's a little more awkward.

If you want it to be conditional on a per-page basis, you could alter your application.html layout to add a new JS include, which will include the raphael library only if it's been told to (via a variable or some other mechanism)

If you add something like :

<%= javascript_include_tag("raphael") if @raphael %>

Obviously changing raphael to whatever the name of the library file actually is, then it will only include if if the @raphael variable is true. This you can set anywhere, either in your controller, or the top of the view, or even in a view helper that you call from the view. Entirely up to you

Upvotes: 1

Related Questions