Include JavaScript files from a control if the files have not been included before
I have written a control requires certain JavaScript files to run, like
jquery-1.5.1.min.js jquery.colorbox.js and another custom file, lets call it gallery.jsI'm thinking about how I can make the control more reusable on different content pages, without the need to load the scripts on pagelevel with the ScriptManagerProxy, meaning that I don't need to do this on every content page:
<asp:ScriptManagerProxy ID="proxy1" runat="server">
<Scripts>
<asp:S开发者_如何学编程criptReference Path="~/scripts/jquery-1.5.1.min.js" />
<asp:ScriptReference Path="~/scripts/jquery.colorbox.js" />
<asp:ScriptReference Path="~/scripts/gallery.js" />
</Scripts>
</asp:ScriptManagerProxy>
That implementation has one disadvantage. If I want to use the control on another page, I'd have to think about the scripts being required. I would rather use an implementation where the control itself loads the necessary JavaScript files, without loading certain scripts more then once. Let's assume I use my control three times on the same page, so I don't want to end up loading all the JavaScript files three times. What can I do?
I'm looking for a solution like this:
if(Page.Scripts["path to javascript file"] == null)
{
Page.Scripts.InsertJavaScript("path to javascript file");
}
How can I proceed in this situation? (I don't want to load the scripts on a pagelevel or in a masterpage to produce unnecessary overhead)
Check RegisterClientScriptInclude:
if (!Page.ClientScript.IsClientScriptIncludeRegistered(typeof(MyControl), "someName")) {
Page.ClientScript.RegisterClientScriptInclude(typeof(MyControl), "someName", ResolveUrl("./something.js"));
}
Use the ClientScript.RegisterXYZ methods which take a Type and a Key. ASP.Net will only output each unique script once.
I belive you can do something like this:
ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "scriptName", "the script url);
This will register the include script only once. It uses the scriptName to register it and it does not register it twice.
精彩评论