How to refresh a page with Turbolinks

前端 未结 3 560
感动是毒
感动是毒 2021-02-07 09:09

I understand that I can call the following code on Turbolinks 5 but it changes the scroll position. Is there a way to call Turbolinks to refresh the page and not change the scro

3条回答
  •  Happy的楠姐
    2021-02-07 09:52

    Store the current scroll position before calling visit, then when the page loads, scroll to that stored position. Resetting the stored scroll position to null ensures that subsequent page loads will not scroll to an old position. One possible implementation might be:

    var reloadWithTurbolinks = (function () {
      var scrollPosition
    
      function reload () {
        scrollPosition = [window.scrollX, window.scrollY]
        Turbolinks.visit(window.location.toString(), { action: 'replace' })
      }
    
      document.addEventListener('turbolinks:load', function () {
        if (scrollPosition) {
          window.scrollTo.apply(window, scrollPosition)
          scrollPosition = null
        }
      })
    
      return reload
    })()
    

    Then you can call reloadWithTurbolinks().

    To prevent the page from flickering as it scrolls from the top to the desired position, add the no-preview cache directive in the page's head:

    
    

提交回复
热议问题