Blazor javascript load not working in sometimes

Viewed 1982

I called javascript function named 'robotDisplayer.initRobot' in OnAfterRenderAsync but it not worked.

The error message is Microsoft.JSInterop.JSException: Could not find 'robotDisplayer.initRobot' ('robotDisplayer' was undefined). Error: Could not find 'robotDisplayer.initRobot' ('robotDisplayer' was undefined).

So I gave 1.5sec in OnAfterRenderAsync. After 1.5sec, I called javascript function('InitRobotJS') and It worked well

Working codes are below

======== C# code ========

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

async Task lazyInitRobot()
{
    DateTime now = DateTime.Now;
    while (true)
    {
        if ((DateTime.Now - now).TotalSeconds >= 1.5)
            break;
    }
    await InitRobotJS();
}

async Task InitRobotJS()
{
    await JSRuntime.InvokeVoidAsync("robotDisplayer.initRobot");
}

======== javascript code ========

//File name : robot_render.js


function initRobot() {
...
}

window.robotDisplayer = {
    initRobot: () => { initRobot(); },
};

======== _Host.cshtml ========

<script type="module" src="~/js/robot_render.js"></script>

If I remove timer (1.5 sec), the error is occurred all time. Is there time issue to load javascript?

0 Answers
Related