This was a very annoying problem that had a straightforward fix but was hard to track down.

The problem

You have a Rails website using Hotwire/Turbo that is, after clicking a link, skipping to the top before navigating to the requested page. The steps needed to replicate are:

  1. Scroll to the bottom of the current page
  2. Click a link to visit something new
  3. Witness the current page jump to the top for a blip šŸ˜§
  4. Requested page renders

Additionally, it would goof up the previous pageā€™s scroll position if you ever clicked to go back. Because the previous page has skipped to the top prior to changing, it didnā€™t reflect where the user was.

The investigation

I was using Bootstrap 5, which defaults to setting scroll-behavior: smooth. I found some folks wondering if the combination of Bootstrap 5 and Turbo was causing weirdness. I disabled smooth scrolling in Bootstrap, but that didnā€™t fix it.

I found similar issues being discussed that related to data-turbo-track="reload"however, that didnā€™t apply to my site. I even found a lengthy discussion dealing with scroll position that is still open.

The solution

As it turns out, my problem wasnā€™t even in the ballpark of any of the stuff above. It was a Cloudflare issue. What?! Yup, there was a little feature turned on in Cloudflare called Rocket Loader. It claims to ā€œImprove the paint time for pages which include JavaScript.ā€ Well, it may very well do that but it screws up Turbo so itā€™s a no-go for a lot of Rails apps.

Rocket Loader setting on Cloudflare

The setting is found under Speed > Optimization > Rocket Loader.

Hopefully, this fixes your problem!

Written by Matt Haliski

The First of His Name, Consumer of Tacos, Operator of Computers, Mower of Grass, Father of the Unsleeper, King of Bad Function Names, Feeder of AI Overlords.