How to refresh a page with Turbolinks

前端 未结 3 550
感动是毒
感动是毒 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条回答
  •  抹茶落季
    2021-02-07 09:34

    My answer is based on Dom Christie's answer, with restored focus after reload and getting the scrollPosition just before rendering.

    Store the current scroll position and active field item before rendering the new page, then after the the is rendered, scroll to that stored position and restore the focus. Resetting the stored scroll position and focusId to null ensures that subsequent page loads will not scroll to an old position/ Focus.

    Note that the fields must have assigned ids in order to recover the focus.

    var reloadWithTurbolinks = (function () {
            var scrollPosition;
            var focusId;
    
            function reload() {
                Turbolinks.visit(window.location.toString(), {action: 'replace'})
            }
    
            document.addEventListener('turbolinks:before-render', function () {
                scrollPosition = [window.scrollX, window.scrollY];
                focusId = document.activeElement.id;
            });
            document.addEventListener('turbolinks:load', function () {
                if (scrollPosition) {
                    window.scrollTo.apply(window, scrollPosition);
                    scrollPosition = null
                }
                if (focusId) {
                    document.getElementById(focusId).focus();
                    focusId = null;
                }
            });
            return reload;
        })();
    

    Then you can call it like this:

     setInterval(function () {
            reloadWithTurbolinks();
     }, 3000);
    

    I combined it with the 'data-turbolinks-permanent' attribute on the form. I also use .

提交回复
热议问题