Question

I have an ASP.NET server control which relies on JQuery for certain functionality. I've tried to add as a webresource.

My problem is my method of including the jquery file adds it to the body, or the form to be exact:

this.Page.ClientScript.RegisterClientScriptInclude(...)

The alternative to this is to add it as a literal in the head tag:

LiteralControl include = new LiteralControl(jslink);
this.Page.Header.Controls.Add(include);

The problem with this however is any existing code srcs in the head which use JQuery fail, as JQuery is loaded afterwards (ASP.NET adds the literal at the bottom of the control tree).

Is there a practical way of making JQuery an embedded resource, but loaded in the head first? Or should I give up now.

Was it helpful?

Solution 2

Update:

A far easier way of doing it is to simply add the script tag dynamically, in your script and point to the google code hosting. e.g.

function include_dom(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}

include_dom("http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js");

The function is taken from this article


Crecentfresh pushed me in the right direction, I also found

http://en.csharp-online.net/Creating_Custom_ASP.NET_AJAX_Client_Controls—IScriptControl.GetScriptReferences_Method.

My problem still remains though, the ScriptManager adds the references after the script in the head but I think this is an issue that can't be resolved. I've opted to answer myself but also upvoted crescentfresh.

OTHER TIPS

If you want to package up jQuery and embed it inside your own server control you should serve it to the client using the ScriptManager. From the top of my head you have to:

  1. add jQuery.js to your project
  2. under its "Build Action" Property, make it an Embedded Resource
  3. in the AssemblyInfo.cs for your control add

    [assembly: WebResource("<Your Server Control namespace>.jQuery.js", "application/x-javascript")]
    
  4. Make your control inherit from System.Web.UI.ScriptControl (or at least implement IScriptControl)

  5. Override GetScriptReferences:

    protected override IEnumerable<ScriptReference>
    GetScriptReferences()
    {
    return new ScriptReference[] { 
        new ScriptReference("<Your Server Control namespace>.jQuery.js", this.GetType().Assembly.FullName),
    };
    }
    

All of your own client script should be setup inside:

protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors()

Which will then ensure the correct order of dependencies (ie jQuery will be available to your own client script).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top