Fixing page jump in Rails websites using Turbo
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:
- Scroll to the bottom of the current page
- Click a link to visit something new
- Witness the current page jump to the top for a blip š§
- 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.
The setting is found under Speed > Optimization > Rocket Loader.
Hopefully, this fixes your problem!