如何使用 Turbolinks 刷新页面 [英] How to refresh a page with Turbolinks
问题描述
我知道我可以在 Turbolinks 5 上调用以下代码,但它会更改滚动位置.有没有办法调用 Turbolinks 来刷新页面而不改变滚动位置?
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 scroll position?
Turbolinks.visit(location.toString());
这会做我想要的,但希望使用 Turbolinks
This will do what I want, but was hoping to use Turbolinks
window.location.reload()
推荐答案
在调用 visit
之前存储当前滚动位置,然后在页面加载时滚动到该存储位置.将存储的滚动位置重置为 null
可确保后续页面加载不会滚动到旧位置.一种可能的实现可能是:
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
})()
然后你可以调用reloadWithTurbolinks()
.
为了防止页面在从顶部滚动到所需位置时闪烁,在页面的head
中添加no-preview
缓存指令:
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
:
<meta name="turbolinks-cache-control" content="no-preview">
这篇关于如何使用 Turbolinks 刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!