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.

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:

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

kinopyo avatar
Written By

kinopyo

Indoor enthusiast, web developer, and former hardcore RTS gamer. #parenting
Published in Rails
Enjoyed the post?

Clap to support the author, help others find it, and make your opinion count.