简体   繁体   English

如何在每个局部视图中完全包含一次外部JavaScript文件?

[英]How can I include an external JavaScript file exactly once per partial view?

I have a partial view (UserControl) that implements a simple pager in my Asp.Net MVC project. 我有一个局部视图(UserControl),它在Asp.Net MVC项目中实现了一个简单的寻呼机。 This pager needs access to a .js file that needs to be included exactly once, regardless of how many instances of the pager control are present on the parent page. 无论母页面上有多少个分页控件实例,此分页器都需要访问一次仅需要包含一次的.js文件。

I've tried to use Page.ClientScript.RegisterClientScriptInclude , but it had no effect (I assume because the code nugget was evaluated too late to impact the head control). 我尝试使用Page.ClientScript.RegisterClientScriptInclude ,但是它没有任何效果(我认为是因为对代码块的评估太迟而无法影响头部控件)。 Is there any simple alternative? 有没有简单的选择?

Add it to the master page. 将其添加到母版页。

Then you can guarantee that it'll only be included once, and you won't forget it.With modern caching, there is really no performance loss on including it on every page. 这样您就可以保证仅将其包含一次,并且您不会忘记它。借助现代缓存,在每个页面上包含它的确没有性能损失。

Set a flag in HttpContext.Current.Items when you send the script in your partial - it's a dictionary that lingers for the whole request. 在部分发送脚本时,在HttpContext.Current.Items中设置一个标志-这是一本字典,可以满足整个请求。 Eg: 例如:

if (!HttpContext.Current.Items.Contains("SentTheScript"))
{
    HttpContext.Current.Items["SentTheScript"] = true;
    Response.Write(Html.ScriptTag("Script"));
}

This way it'll be rendered at most once. 这样,它将最多渲染一次。

Page.ClientScript.RegisterClientScriptInclude is used with the traditional ASP.net. Page.ClientScript.RegisterClientScriptInclude与传统的ASP.net一起使用。

Since you using asp.net-mvc, all you need is to add the script directive of the js file to the page that uses this user control. 由于您使用的是asp.net-mvc,因此只需将js文件的script指令添加到使用此用户控件的页面即可。

Since it's a good practice to have only one minified css file to all the site, you probably will want to include this file in the main css minified file. 由于最好的做法是在所有站点上只有一个缩小的CSS文件,因此您可能希望将此文件包括在主要的缩小CSS文件中。

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

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