Neil Neil - 2 months ago 15
Javascript Question

Loading spinner and message displaying when back button clicked

When links on my page are clicked, a spinner and a message appear on the page. It works, and they disappear appropriately when the new page is loaded in.

I utilized spin.js found here to implement the loading spinner.

I found a bug though. When a user clicks the back button on their browser, it goes back to the previous page, but in the state of displaying the spinner and error message. I want to of course go back to the state where the message is hidden and the spinner is not showing.

According to this post, it sounds like the issue might have to do with cacheing.

I am using the


Below is my code:

$(document).ready(function(){ #for turbolinks compatability
(function default_hide_waiting_message(){
(function display_loading_spinner_and_message(){
$(".show_loading_spinner_on_click").on('click', function(){
var opts = {
lines: 12 // The number of lines to draw
, length: 7 // The length of each line
, width: 5 // The line thickness
, radius: 10 // The radius of the inner circle
, scale: 1.0 // Scales overall size of the spinner
, corners: 1 // Roundness (0..1)
, color: '#000' // #rgb or #rrggbb
, opacity: 1/4 // Opacity of the lines
, rotate: 0 // Rotation offset
, direction: 1 // 1: clockwise, -1: counterclockwise
, speed: 1 // Rounds per second
, trail: 100 // Afterglow percentage
, fps: 20 // Frames per second when using setTimeout()
, zIndex: 2e9 // Use a high z-index by default
, className: 'spinner' // CSS class to assign to the element
, top: '50%' // center vertically
, left: '50%' // center horizontally
, shadow: false // Whether to render a shadow
, hwaccel: false // Whether to use hardware acceleration (might be buggy)
, position: 'absolute' // Element positioning
var target = document.getElementById('spinner')
var spinner = new Spinner(opts).spin(target)


The issue is happening because the $(document).ready function isn't getting called when you hit back. You'll need to update your javascript to accommodate Turbolinks.

Instead of using $(document).ready try using the appropriate page event, such as page:load. The available options are listed in the Turbolinks docs

Your final javascript would have something similar to $(document).on("page:fetch", default_hide_waiting_message)