Prevent loading multiple JavaScript scripts 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 call them more than once, for example:

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

this would be ambiguous because the function sayHellowould be enabled three times, which is not necessary.

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

+4
source share
2 answers

I don't think there is a way on the server side to solve this problem. But with Javascript and JQuery you can solve this problem.

script scripts.js js wwwroot. , SayHello undefined, , , undefined, script, JQuery getcript .

.

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

,

0

, ScriptIncluded, , script , - ; ScriptIncluded, true :

<button type="button" onClick="sayHello">&lt/button&gt
@if(model.ScriptIncluded){
    <script&gt
        function sayHello(){
        }
    </script&gt
}

model.ScriptIncluded = True;, . bool HttpContext.Items.

0

Source: https://habr.com/ru/post/1651282/


All Articles