3

I have developed a custom control (not user control), which uses some jQuery scripting.

I have embedded the control's script as a embedded resource into the Assembly and have it registered in the Page at the OnPreRender event, like this:

protected override void OnPreRender(EventArgs e)
{
   string controlScript = "Namespace.MyScript.js";
   ClientScriptManager csm = this.Page.ClientScript;
   csm.RegisterClientScriptResource(typeof(ResourceFinder), controlScript );
   base.OnPreRender(e);
}

This control works when deployed in a project with the jQuery Library already in place, but what if the jQuery library is not available. How would I check if the library is already in the project, and if not, then embed it in the assembly as well and pull it from there. I was thinking something like:

protected override void OnPreRender(EventArgs e)
{
    ClientScriptManager csm = this.Page.ClientScript;

    // Here I would need to check if jQuery is already registered
    // but there is no such method like: IsClientScriptResourceRegistered
    if (csm.IsClientScriptResourceRegistered("jQuery"))
    {
        string jQueryLib = "Namespace.jquery-1.7.2.min.js";
        csm.RegisterClientScriptResource(typeof(ResourceFinder), jQueryLib);
    }

    string controlScript = "Namespace.MyScript.js";
    csm.RegisterClientScriptResource(typeof(ResourceFinder), controlScript );
    base.OnPreRender(e);
}

I know I could embed the jQuery library in the assembly anyway, but if jQuery was already in project then I would end up with a page with two calls to the libray, like this:

<!-- Project's jQuery lib -->
<script type="text/javascript" src="/scripts/jquery-1.7.2.min.js"></script>
<!-- DLL's duplicated jQuery lib:  -->
<script type="text/javascript" src="/WebResource.axd?d=AP7y...r0bHQl"></script>
<!-- DLL Control's MyScript.js -->
<script type="text/javascript" src="/WebResource.axd?d=uTGR...ur15b"></script>

...which is what I'm trying to avoid.

Any ideas?

alonso.torres
  • 1,199
  • 2
  • 12
  • 26
  • I was thinking that maybe instead of registering the jQuery library directly I could register a script block that checks for jquery availability first as stated in [this other question](http://stackoverflow.com/questions/1014203/best-way-to-use-googles-hosted-jquery-but-fall-back-to-my-hosted-library-on-go). – alonso.torres Apr 26 '12 at 15:24

1 Answers1

1

Insert a script tag to test for the jQuery object using a short circuiting operator. If jQuery is not available, make it available.

<script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.1.min.js"><\/script>')</script>
JackMahoney
  • 3,423
  • 7
  • 32
  • 50