简体   繁体   中英

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?

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

I think you should define a property like ScriptIncluded to specify whether the script included in the model, and in server side to maintain the property status; Check the ScriptIncluded property whether true every time when invoke the component like this:

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

In your component class definition, you should set the model.ScriptIncluded = True; if the component is not invoked first time. You can keep a bool value in HttpContext.Items .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM