How can I include an external JavaScript file exactly once per partial view?
I have a partial view (UserControl) that implements 开发者_如何学JAVAa simple pager in my Asp.Net MVC project. 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.
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). Is there any simple alternative?
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. E.g.:
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.
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.
Page.ClientScript.RegisterClientScriptInclude
is used with the traditional 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.
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.
精彩评论