Home > Back-end >  How to load a script tag after loading all components in Blazor
How to load a script tag after loading all components in Blazor

Time:03-06

In wwwroot/index.html (Blazor WebAssembly) or Pages/_Host.cshtml (Blazor Server) we can add a <script src="?"/> tag.

<body>
    ...

    <script src="_framework/blazor.{webassembly|server}.js"></script>
    <script src="?"></script> // I want to load this script after all components/site completely loaded.
</body>

But the problem is the <script src="?"/> tag just loaded but I want to load it after loading all components of Blazor. (Some functions inside the script cannot find some elements)

There is a way to load a JS function like below

@page "/"

 @inject IJSRuntime JSRuntime

    <div>
        this is index page
    </div>
@code {

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JSRuntime.InvokeVoidAsync("initilizeNiceAdminJs");// Initialize main.js after site completely loaded
        }
    }
}

The OnAfterRenderAsync method helps us to load a JS function after loading entire components in the Blazor.

Does exist any way to do the same with a <script src="?"/> tags instead of a function?

CodePudding user response:

You have several ways to do this

  1. Inject a script after Blazor starts this is used to load js after blazor app started

  2. Load a script from an external JavaScript file (.js) collocated with a component on this way you can define a javascript file for each compponent

  3. use your own javascript loader

this code can invoke callback function from blazor app. for this you must register your instance first and you can call it from your blazor app

App = {};

App.LoadScript = (function (Url, Instance, CallBack) {
    var head = document.head;
    var IsExist = false;
    var Scripts = head.getElementsByTagName('script');
    for (var i = Scripts.length; i--;) {
        var Src = Scripts[i];
        if (Src.src == Url || Src.src.replace(Src.baseURI, '') == Url) {
            IsExist = true;
            break;
        }
    }
    if (!IsExist) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = Url;
        if (CallBack && Instance) {
            script.onload = setTimeout(() => { App.CsharpInvoker(Instance, CallBack); }, 3000);
        }
        else if (CallBack)
            script.onload = setTimeout(() => { CallBack(); }, 1000);

        head.appendChild(script);
    }
    else if (CallBack && Instance)
        setTimeout(() => { App.CsharpInvoker(Instance, CallBack); }, 1000);
    else if (CallBack)
        setTimeout(() => { CallBack(); }, 1000);
});

App.CsharpInvoker = (function CSharpCallBackInvoker(Instance, MethodName, Parameter) {
    Instance.invokeMethodAsync(MethodName, Parameter);
});
  • Related