Search code examples
javascriptc#asp.net-coreasp.net-core-viewcomponent

Preventing multiple JavaScript scripts loading in Asp.Net Core ViewComponents


For example, I have this PrimitiveViewComponent:

<button type="button" onClick="sayHello"></button>
<script>
    function sayHello() {
        console.log("Hello")
    }
</script>

If I invoke them more than once, like this:

<div>@await Component.InvokeAsync("Primitive")</div>
<div>@await Component.InvokeAsync("Primitive")</div>
<div>@await Component.InvokeAsync("Primitive")</div>

it would be an ambiguity, because the function sayHello would be included three times, which isn't necessary.

How should I define JavaScript functions for ViewComponents, how can I prevent them from being included more than once, and where to store them?


Solution

  • I don't think there is a way in server side to manage this issue. But using Javascript and JQuery you can fix this problem.

    In this code, I moved the script to a file scripts.js under js folder in wwwroot. While loading the page I am checking whether the SayHello is a function or it is undefined, if it is a function means it is loaded to the page, if it is undefined, I am loading the script using JQuery getscript method.

    Here is the view component code.

    <button type="button" onClick="sayHello()">Hello</button>
    <script>
        if (typeof sayHello !== 'function') {
            $.getScript( "/js/scripts.js" ).done(function( script, textStatus ) {
                console.log( textStatus );
            });
        }
    </script>
    

    Hope it helps