I use Blazor to dynamically load part of the page content. First, I use js to listen to the scroll bar and call back the loading data method in the Blazor page.
let lock = false;
window.setupScrollListener = (objRef) => {
window.addEventListener("scroll", () => {
if (lock) {
return;
}
const scrollTop =
document.documentElement.scrollTop || document.body.scrollTop;
const windowHeight =
document.documentElement.clientHeight || document.body.clientHeight;
const scrollHeight =
document.documentElement.scrollHeight || document.body.scrollHeight;
let delta = Math.abs(scrollTop + windowHeight - scrollHeight);
if (delta > 0 && delta < 100) {
lock = true;
setTimeout(() => {
objRef.invokeMethodAsync("LoadMoreData")
.then((result) => (lock = false))
.catch((error) => console.error(error));
}, 500);
}
});
};
blazor code
@page "/"
@using XMagic.Client.Shared
@rendermode @(new InteractiveAutoRenderMode(prerender: false))
<a href="/">index</a>
<a href="/test">test</a>
<div class="flex mx-auto">
<div class="flex flex-col gap-4">
@foreach (var img in _col1)
{
<Image Src="@img"/>
}
</div>
</div>
@code {
List<string> _col1 = ["images/01.jpeg", "images/banner1.jpeg", "images/01.jpeg"];
[Inject] IJSRuntime? JsRuntime { get; set; } = default!;
DotNetObjectReference<Test>? _objRef;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
_objRef = DotNetObjectReference.Create(this);
if (JsRuntime != null)
{
await JsRuntime.InvokeVoidAsync("setupScrollListener", _objRef);
}
}
}
[JSInvokable]
public bool LoadMoreData()
{
_col1.Add("images/01.jpeg");
_col1.Add("images/banner1.jpeg");
_col1.Add("images/01.jpeg");
Console.WriteLine("LoadMoreData Exec...");
Console.WriteLine(_col1.Count);
StateHasChanged();
return true;
}
public void Dispose() => _objRef?.Dispose();
}
After entering localhost:port in the browser address bar to access the index page, LoadMoreData will be called when the scroll bar scrolls to the bottom, and the page content will be updated.
But when I click <a href=”/test”>test</a> to enter a new page, and then return to the index page through <a href=”/”>index</a>, when the scroll bar scrolls LoadMoreData will also be called when reaching the bottom, but the page content is not updated.
I hope to solve this problem so that the page content can be loaded dynamically.