Let's picture this, you have started making a Rails application and you're excited to use JavaScript/jQuery in it, but when you run the app your JavaScript only works if you have reloaded the page, and not if you're navigating to it from some other page in your app. A weird problem, you might as well say!
Rails is shipped with a gem called Turbolinks which prevents your browser from loading the whole page every time you send a request, making them faster. Here is how they describe the gem on their GitHub page:
You might be asking, what all this has to do with your problem, I was just coming to that. Now in your rails app, when you navigate from other page to your target page, instead of reloading the JavaScript again, it maintains the instance from the earlier page, and that's the reason why it doesn't work unless you reload your target page.
There are many workarounds to this problem, but the tidiest way I have come across is to add a gem called jQuery Turbolinks. Just add this line to your Gemfile and run bundle update
gem 'jquery-turbolinks'
then in your application.js file, require this in this particular order
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//
// ... your other scripts here ...
//
//= require turbolinks
Now all you need to do is to restart your rails server, and you're good to go! Happy hacking!
Rails is shipped with a gem called Turbolinks which prevents your browser from loading the whole page every time you send a request, making them faster. Here is how they describe the gem on their GitHub page:
You might be asking, what all this has to do with your problem, I was just coming to that. Now in your rails app, when you navigate from other page to your target page, instead of reloading the JavaScript again, it maintains the instance from the earlier page, and that's the reason why it doesn't work unless you reload your target page.
There are many workarounds to this problem, but the tidiest way I have come across is to add a gem called jQuery Turbolinks. Just add this line to your Gemfile and run bundle update
gem 'jquery-turbolinks'
then in your application.js file, require this in this particular order
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//
// ... your other scripts here ...
//
//= require turbolinks
Now all you need to do is to restart your rails server, and you're good to go! Happy hacking!
No comments:
Post a Comment