Tuesday, February 07, 2017

$ is not defined error in Rails

I followed the Google Page Speed Guidelines and made the javascript load asynchronously to speed up rubyplus.com. The problem was that I was getting the $ is not defined error. I had included the javascript tag before the jQuery script that hides the notice. Eventually, I came across this post:
Rails 4 Gotcha Asynchronous Loading of Javascript that finally fixed the problem. The fix is:

Change:

  <%= javascript_include_tag "application", "data-turbolinks-track" => true, async: true %>

to

  <%= javascript_include_tag "application", "data-turbolinks-track" => true, async: Rails.env.production? %>

I know this is a quick hack. Ideally, we should define a configuration variable to read and set the flag value in development.rb and production.rb. That's for another iteration and deploy. It works in development, now, I will see how it works in production for some time.