Explain Codes LogoExplain Codes Logo

Rails 4: how to use $(document).ready() with turbo-links

javascript
event-handling
turbolinks
rails
Alex KataevbyAlex Kataev·Sep 22, 2024
TLDR

Instead of relying on $(document).ready(), utilise $(document).on('turbolinks:load', function()) effectively triggering JavaScript events with TurboLinks in Rails 4.

$(document).on('turbolinks:load', function() { // This is where the magic happens... });

Correlating TurboLinks and jQuery, we can especialize how events bind, ensure idempotent functions, and manage files.

Traditional $(document).ready might not play well with TurboLinks. Instead, utilize page:load with jQuery in Rails 4. Fun fact, TurboLinks got its name because it "links" you to your desired page at "turbo" speed.

$(document).on('page:load', function() { // jQuery is now Turbo-Charged! });

Preventing event re-binding

Avoid re-binding events for increased efficiency on every page:load. Highly efficient, much wow!

if (!eventAlreadyBound) { // Call doge, bind event here. }

Enter jquery.turbolinks, a deprecated yet handy gem that patches TurboLinks and jQuery event issues.

//= require jquery.turbolinks // Unleash the undead magic of deprecated gems.

Rewrite scripts to properly work with TurboLinks without reliance on 'ready' events. This makes your scripts nice and TurboLinks-friendly, like a well-trained pet.

$(document).on('turbolinks:load', function() { // The TurboLinks school of JavaScript - Enroll Today! });

A comprehensive event handling approach

With $(document).on('ready page:load'), we can handle both initial page load and TurboLinks load.

$(document).on('ready page:load', function() { // Double the functionality, double the fun! });

Efficient file organization with the asset pipeline

For better file organization, load scripts via application.js manifest. It's like arranging your bookshelf!

//= require tree . // I speak for the JS, for the JS has no tongues.

Understanding how TurboLinks works with different versions of Rails, efficient event bindings, and working with Rails helpers leads to an optimized user experience.

In Rails 4.2 and above, using turbolinks:load makes jQuery events work seamlessly.

$(document).on('turbolinks:load', function() { // Like PB&J, jQuery and TurboLinks are better together. });

Event-Proof Scripts

Here's a resilient way to ensure your scripts thrive, not just survive, in the TurboLinks ecosystem.

$(document).on('turbolinks:load', function() { // Scripts built to last! });

The Rails Way

Align your JavaScript coding style with the Rails way by deciphering the Rails guide or dive into some quality third-party resources.

$(document).on('turbolinks:load', function() { // When in Rails, do as the Rails do. });