I have an ASP.NET WebUserControl that requires a JavaScript to function correctly. My goal is to not include the JavaScript in any of my Page or Masterpage whenever I consume the WebUserControl. All I want to do is just drag and drop one or more of the WebUserControl on to my page and I'll be good to go. I can solve this maze by loading the JavaScript in my WebUserControl dynamically. But it will load duplicates JavaScript on my page if I have more than one of the identical WebUserControl. If you happen to come across into this kind of situation, here is the solution on how to prevent loading duplicate JavaScript on your page. It works for me, comments are welcome.
Use this code in the WebUserControl
protected void Page_Load(object sender, EventArgs e)
{
LoadJScript();
}
//load the javascript
internal void LoadJScript()
{
ClientScriptManager script = Page.ClientScript;
//prevent duplicate script
if (!script.IsStartupScriptRegistered(this.GetType(), "MultipleSelectionDDLJS"))
{
script.RegisterStartupScript(this.GetType(), "MultipleSelectionDDLJS",
"<script type='text/javascript' src='JScript.js'></script>");
}
}
Reference