Home >Web Front-end >JS Tutorial >How to Make jQuery's `$(document).ready()` Work with Rails 4's Turbo Links?
Rails 4: Utilizing jQuery's '$(document).ready()' with Turbo-Links Integration
While working on a Rails 4 application, developers often encounter the need to organize their JavaScript files effectively. Traditionally, JavaScript code was scattered across various views. However, a more organized approach involves compiling them into separate files and utilizing the assets pipeline.
However, when Turbo-Links is enabled, the jQuery "ready" event encounters a limitation. During subsequent clicks, the "ready" event ceases to fire, affecting the execution of code within its scope. This issue arises due to the fact that the page doesn't reload with Turbo-Links enabled.
To resolve this, it is essential to ensure that jQuery events function flawlessly while Turbo-Links remains active. Two approaches can be considered:
Approach 1: Event Wrapping with Rails-Specific Listener
This method involves wrapping JavaScript scripts within a Rails-specific listener, effectively ensuring their execution upon page load.
Approach 2: Utilizing Turbo-Links Event
Turbo-Links provides a specific event, "page:load," that can be used to trigger necessary JavaScript code. By leveraging this event, developers can bypass the issue caused by subsequent clicks.
For CoffeeScript users, the following code snippet offers a solution:
ready = -> ...your coffeescript goes here... $(document).ready(ready) $(document).on('page:load', ready)
The last line of this snippet listens for the "page:load" event, which Turbo-Links triggers.
For JavaScript users, the following equivalent code can be employed:
var ready; ready = function() { ...your javascript goes here... }; $(document).ready(ready); $(document).on('page:load', ready);
In Rails 5, with the updated Turbolinks 5, the "page:load" event has been replaced with "turbolinks:load," which is triggered even on initial page load. This simplifies the code to the following:
$(document).on('turbolinks:load', function() { ...your javascript goes here... });
By implementing these solutions, developers can effectively ensure that jQuery events continue functioning correctly despite the presence of Turbo-Links.
The above is the detailed content of How to Make jQuery's `$(document).ready()` Work with Rails 4's Turbo Links?. For more information, please follow other related articles on the PHP Chinese website!