How do I add a javascript file from a UserControl to an ASP.NET page only once?

1.7k views Asked by At

I have an ASP.NET UserControl that requires a javascript file. It's a jQuery plugin. I want to add this file only when I use the UserControl on a page. Because it's a jQuery plugin, I need it to be added after the jQuery file is added.

Because of master pages and such, when I use RegisterClientScriptInclude, the script is added before the jQuery script and doesn't work.

RegisterStartupScript would do the trick, but doesn't seem to work with a javascript file (it does if you provide the actual javascript code).

What's more, I don't want the control to add the script twice if I add it to the page twice.

It seems this must be trivial, but I can't get it to work.

1

There are 1 answers

3
nativehr On BEST ANSWER

RegisterStartupScript can register js files as well.

var clientScriptManager = Page.ClientScript;

if(!clientScriptManager.IsStartupScriptRegistered("a_plugin"))
{
    clientScriptManager.RegisterStartupScript(Page.GetType(), "a_plugin", "<script src=\"/js/a_plugin.js\"></script>");
}