简体   繁体   English

防止在Asp.Net Core ViewComponents中加载多个JavaScript脚本

[英]Preventing multiple JavaScript scripts loading in Asp.Net Core ViewComponents

For example, I have this PrimitiveViewComponent : 例如,我有这个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. 这将是一个模棱两可,因为函数sayHello将被包括三次,这是没有必要的。

How should I define JavaScript functions for ViewComponents, how can I prevent them from being included more than once, and where to store them? 我应该如何为ViewComponents定义JavaScript函数,如何防止它们被多次包含,以及在哪里存储它们?

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. 但是使用Javascript和JQuery可以解决这个问题。

In this code, I moved the script to a file scripts.js under js folder in wwwroot. 在这段代码中,我将脚本移动到wwwroot中js文件夹下的scripts.js文件中。 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. 在加载页面时,我正在检查SayHello是一个函数还是未定义,如果它是一个函数意味着它被加载到页面,如果它是未定义的,我使用JQuery getscript方法加载脚本。

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; 我认为你应该定义一个像ScriptIncluded这样的属性来指定脚本是否包含在模型中,并在服务器端保持属性状态; Check the ScriptIncluded property whether true every time when invoke the component like this: 每次调用组件时,检查ScriptIncluded属性是否为true,如下所示:

<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; 在组件类定义中,您应该设置model.ScriptIncluded = True; if the component is not invoked first time. 如果第一次没有调用该组件。 You can keep a bool value in HttpContext.Items . 您可以在HttpContext.Items保留bool值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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