Search code examples
javascriptasp.netwebformsasp.net-controls

ScriptControl WebResource Loading Order


I am adding a new control to a project that has some ASP.Net controls. Each control essentially comprises of a .Net class (inheriting ScriptControl) and a javascript file. Each of the js files are added to the assembly as a WebResource

[assembly: WebResource("Assembly.Namespace.WidgetControl.js", "text/javascript")]
[assembly: WebResource("Assembly.Namespace.CogControl.js", "text/javascript")]

I'm wanting to inherit from a "class" in another javascript resource from one of the other controls because otherwise I would need to copy/paste code some of the function code from the js class I want to inherit from which is ugly, ugly, ugly for maintenance. I'm not a fan of duplicated efforts.

Now, what I am after is WebResource loading order. Let's say, for demonstrative purposes, I would like to inherit from the class in WidgetControl.js and extend it with ThingaMahBobControl.js. Does adding the WebResource assembly reference for ThingaMahBob after Widget guarantee load order?

I can't inherit from something that has not yet been loaded, so this is vital. Since the control is inheriting the abstract ScriptControl, it has to implement GetScriptReferences() so would returning the enumerable collection of references in the desired order work? i.e.:

protected override IEnumerable<ScriptReference> GetScriptReferences()
{
    List<ScriptReference> refs = new List<ScriptReference>();
    refs.Add(new ScriptReference("Assembly.Namespace.WidgetControl.js", this.GetType().Assembly.FullName));
    refs.Add(new ScriptReference("Assembly.Namespace.ThingaMahBobControl.js", this.GetType().Assembly.FullName));
    return refs;
}

Solution

  • Yes, this will work. If in GetScriptReferences you will specifiy full collection of the script reference required for you control then this will work. Note: that duplicated script reference simply will not be added by script manager. But the main point here is that you need to specify full collection of the script your control depends on.

    I also have a suggestion to look at the way it is implemented in Ajax Control Toolkit (or for example the same approach is used in Telerik ASP.NET Ajax Controls). There are exist ClientScriptResource and RequiredScript attributes and ScriptObjectBuilder helper class which helps to resolve such type of ordering problems.