Merge pull request #4266 from sbwalker/dev

improve scroll position navigation behavior
This commit is contained in:
Shaun Walker 2024-05-17 15:42:26 -04:00 committed by GitHub
commit 4b1f23a189
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 19 additions and 13 deletions

View File

@ -187,7 +187,7 @@
} }
@if (_renderMode == RenderModes.Static) @if (_renderMode == RenderModes.Static)
{ {
_scrollPositionScript = "<page-script src=\"/js/scrollposition.js\"></page-script>"; _scrollPositionScript = CreateScrollPositionScript();
} }
_headResources += ParseScripts(site.HeadContent); _headResources += ParseScripts(site.HeadContent);
@ -488,6 +488,24 @@
"</script>"; "</script>";
} }
private string CreateScrollPositionScript()
{
return
"<script>" + Environment.NewLine +
" window.interceptNavigation = () => {" + Environment.NewLine +
" let currentUrl = window.location.href;" + Environment.NewLine +
" Blazor.addEventListener('enhancedload', () => {" + Environment.NewLine +
" let newUrl = window.location.href;" + Environment.NewLine +
" if (currentUrl != newUrl) {" + Environment.NewLine +
" window.scrollTo({ top: 0, left: 0, behavior: 'instant' });" + Environment.NewLine +
" }" + Environment.NewLine +
" currentUrl = newUrl;" + Environment.NewLine +
" });" + Environment.NewLine +
" };" + Environment.NewLine +
" document.onload += window.interceptNavigation();" + Environment.NewLine +
"</script>";
}
private string ParseScripts(string content) private string ParseScripts(string content)
{ {
// iterate scripts // iterate scripts

View File

@ -1,12 +0,0 @@
function setScrollPosition() {
window.scrollTo({
top: 0,
left: 0,
behavior: 'instant'
});
}
export function onUpdate() {
setScrollPosition();
}