I have an application that uses a lot of javascript in a lot of different .js files.
Each page can have any number and combination of different controls and each control can use a different set of js files.
Instead of including all possible js files as <script src="xxx.js">
in the head of my master page, I thought I would reduce the amount of included files by getting each control to call
ScriptManager.Scripts.Add(new ScriptReference("xxx.js"))
- thus only the scripts that are actually needed by the page will be included.
Well that bit works fine. But...the controls also use ScriptManager.RegisterClientScriptBlock
fairly extensively too. (There are scenarios where the controls are inside update panels).
I was disappointed to see that the ScriptManager emits the client script includes before the ScriptReferences. For example - see the test file and output at the end (this results in a JS error because $ is not defined).
Am I being dumb or is this to be expected? I would have thought that a sensible thing for the ScriptManger to do would be to emit the ScriptReferences first and then the other stuff.
Short of rolling my own ScriptManager like object to manage static JS file references, does anyone have any suggestions as to get the behaviour that I want from ScriptManager??
Thanks in advance.
Example File
<%@ Page Language="C#" AutoEventWireup="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "Test", "$(function() {alert('hello');});", true); } </script> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager runat="server" > <Scripts> <asp:ScriptReference Path="~/jquery/jquery.js" /> </Scripts> </asp:ScriptManager> </form> </body> </html>
Output
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > ... boring stuff removed .... <script src="/js/WebResource.axd?d=-nOHbla bla " type="text/javascript"></script> <script type="text/javascript"> //<![CDATA[ $(function() {alert('hello');});//]]> </script> ... boring stuff removed .... <script src="/js/ScriptResource.axd?d=qgCbla bla bla" type="text/javascript"></script> <script src="jquery/jquery.js" type="text/javascript"></script> ... boring stuff removed .... </form> </body> </html>