Load Javascript Blazor component

依然范特西╮ 提交于 2020-12-11 10:01:10

问题


I'm trying to convert my .netcore website into Blazor SPA..80% work is complete. My Facebook Like/Share button is not getting display through .razor page. I put below facebook javascript in index.html and facebook "Div" in my .razor page.

<script>
    (function (d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = 'https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.10&appId=00000000000000';
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));</script>

I think issue is Facebook javascript execute before blazor content render on DOM. Is there any way to bind component javascript with that component only so when my facebook component will display then only facebook javascript will run ?


回答1:


You can use JSInterop call from the OnAfterRenderAsync method, like this:

 @page "/"
 @inject IJSRuntime jsRuntime

 <h1 id="myid" @ref=MyElementReference>Hello, world!</h1>


@code{
    ElementReference MyElementReference;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JSRuntime.InvokeAsync<object>("MyJSMethods.myMethod", MyElementReference);
        }

    }
}

Note: You need to inject the JSRuntime object in order to execute JSInterop calls.

You have to call your JavaScript code after your components have been rendered. The OnAfterRenderAsync method is called after the component has been rendered, and thus you can put code here to initialize your component. This should be when firstRender is true, and multiple calls to your JavaScript objects, when firstRender is false.

Place your script at the bottom of the _Host.cshtml file, just below

<script src="_framework/blazor.server.js"></script>
<script>
        window.MyJSMethods =
        {
            myMethod: function (element) {
                window.alert(element.id);
            }
        };
    </script>

Note that the parameter named element that the function takes is an element object because we defined the argument as ElementReference in Blazor. Of course, you could've passed the element id.



来源:https://stackoverflow.com/questions/59911580/load-javascript-blazor-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!