Prevent Turbolinks from reloading the page when clicking anchor links

kinopyo avatar

Turbolinks sends another server request when clicking an anchor link that points to the same page. For example, when you're in the posts#show page and click an anchor link like #comment-123, it'll hit the posts_controller's show action again to do a full page reload.

You can use the workaround posed from the community to temporary fix this issue.

document.addEventListener("turbolinks:click", (event) => { const anchorElement = const isSamePageAnchor = ( anchorElement.hash && anchorElement.origin === window.location.origin && anchorElement.pathname === window.location.pathname ) if (!isSamePageAnchor) return event.preventDefault() Turbolinks.controller.pushHistoryWithLocationAndRestorationIdentifier(, Turbolinks.uuid() ) })

Import that fix after the original Turbolinks:

import Turbolinks from "turbolinks" import "extensions/turbolinks"

Alternatively, as this comment suggested, you can "add data-turbolinks="false" to the anchor link to opt-out of Turbolinks behavior".

Personally, I prefer to keep the HTML native in this case.