Decrease Font Size
Increase Font Size

ASP ASP.NET load JavaScript dynamically with no duplicate

Using JavaScript Along with ASP.NET |

Using JavaScript Along with ASP.NET 2.0 |

How to load a Javascript file in Asp.Net 2.0? |

Dynamically add JavaScript at pageload |

ASP.NET load JavaScript dynamically with no duplicate


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)

//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>");