October 2, 2023

PureSourceCode

All technologies, only pure source code

Forum

JSInterop is not ad...
 
Share:
Notifications
Clear all

JSInterop is not add the script before OnAfterRenderAsync

0 Posts
1 Users
0 Likes
742 Views
0
Topic starter

I have a component for Blazor. I have a JSInterop that is defined like that

public class JSMarkdownInterop
{
    IJSRuntime jsRuntime;

    public JSMarkdownInterop(IJSRuntime JSRuntime)
    {
        jsRuntime = JSRuntime;

        jsRuntime.InvokeAsync<IJSObjectReference>("import",
            "/_content/PSC.Blazor.Components.MarkdownEditor/js/markdownEditor.js");
    }

    public async ValueTask AddJS(string targetUrl)
    {
        await jsRuntime.InvokeVoidAsync("loadJs", targetUrl);
    }
}

The function loadJS is in the markdownEditor.js. So, in the component I added this code in the OnInitialized function

protected JSMarkdownInterop JSModule { get; private set; }

protected override void OnInitialized()
{
    if (JSModule == null)
        JSModule = new JSMarkdownInterop(JSRuntime);

    base.OnInitialized();
}

then, in the OnAfterRenderAsync I want to call the AddJS function to add some scripts.

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    await base.OnAfterRenderAsync(firstRender);

    if (firstRender)
    {
        await JSModule.AddJS(easyMDEJS);
    }
}

I end up to have an error because apparently the fucntion loadJS was undefined.

enter image description here

How you can see in the above screenshot, there is the error but also the application added the script. Then, I think the application adds the script after the first render.

How can I delay the first render until the script is added? Or how can I add the script on time for the first render?

Update

I changed the JSMarkdownInterop like that

public class JSMarkdownInterop : IAsyncDisposable
{
    private readonly Lazy<Task<IJSObjectReference>> moduleTask;

    public JSMarkdownInterop(IJSRuntime jsRuntime)
    {
        moduleTask = new(() => jsRuntime.InvokeAsync<IJSObjectReference>("import",
            "./_content/PSC.Blazor.Components.MarkdownEditor/js/markdownEditor.js")
            .AsTask());
    }

    public async ValueTask AddJS(string targetUrl)
    {
        var module = await moduleTask.Value;
        await module.InvokeVoidAsync("loadJs", targetUrl);
    }
}

but I receive the same error.

Share: