How can I dictate the order in which scripts are rendered to a page when implementing custom controls using the IScriptControl interface?
Here's an example of what I am doing:
public class MyScriptControl : WebControl, IScriptControl
{
private static ConcurrentBag<ScriptReference> ScriptReferences;
static MyScriptControl()
{
ScriptReferences = new ConcurrentBag<ScriptReference>
{
new ScriptReference { Name = "jquery" },
new ScriptReference { Name = "jquery-ui" },
new ScriptReference { Name = "myscriptcontrol" }
};
ScriptManager.ScriptResourceMapping.AddDefinition("myscriptcontrol",
new ScriptResourceDefinition
{
ResourceAssembly = Assembly.GetCallingAssembly(),
ResourceName = "Path.To.Scripts.myscriptcontrol.js"
}
);
}
public MyScriptControl()
{ }
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ScriptManager.GetCurrent(Page)
.RegisterScriptControl<MyScriptControl>(this);
}
protected override void Render(HtmlTextWriter writer)
{
// Render UI
}
public IEnumerable<ScriptReference> GetScriptReferences()
{
foreach (var reference in ScriptReferences)
{
yield return reference;
}
}
public IEnumerable<ScriptDescriptor> GetScriptDescriptors()
{
return new ScriptDescriptor[] { };
}
}
The code above creates a problem because it renders the jQueryUI script reference before rendering the jQuery script reference. If I change the order, the scripts render in the correct order:
ScriptReferences = new ConcurrentBag<ScriptReference>
{
new ScriptReference { Name = "myscriptcontrol" },
new ScriptReference { Name = "jquery-ui" },
new ScriptReference { Name = "jquery" }
};
This is great for a single control, but I'm developing dozens of internal controls, some of which will have dependencies on 开发者_JAVA技巧jQuery or other libraries, and I want to be sure that no matter what combination of controls are rendered to the page, script references are rendered in the correct order to avoid any dependency issues.
Besides figuring out how to dictate order for dependent scripts, feel free to rip apart any bad practices or problem code you see here.
It is not necessarily the order in which the scripts are declared that determines order. If you have many scripts and many DocumentReady functions, as Jquery loops through and processes each DocumentReady function block, if the document is not ready yet it pushes the function on to a wait stack. If the document is ready, it processes the function immediately. So it is possible and likely that the DocReady calls for your first includes would always execute last and the last ones would execute first since the are processed at the end when the document is finally ready.
This post explains it very well and suggests a workaround for it:
Change Execution Order of DocumentReady
精彩评论