Prevent Turbolinks from reloading the page when clicking anchor links

kinopyo avatar
kinopyo

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.

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

Import that fix after the original Turbolinks:

app/javascript/packs/application.js
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.

Reference: https://github.com/turbolinks/turbolinks/issues/75#issuecomment-445325162