I wish I could easily register which JavaScript and CSS files components of my site need to be able to display properly to the end user. With a little bit of tinkering, now I can.
I added this to the master page code-behind:
private List<string> scriptUrls = new List<string>(); private List<string> styleUrls = new List<string>(); public void AddScriptIfNotAlreadyPresent(string url) { if(!scriptUrls.Contains(url)) scriptUrls.Add(url); } public void AddScriptsIfNotAlreadyPresent(List<string> urls) { foreach (var url in urls) AddScriptIfNotAlreadyPresent(url); } public void AddStyleIfNotAlreadyPresent(string url) { if (!styleUrls.Contains(url)) styleUrls.Add(url); } public void AddStylesIfNotAlreadyPresent(List<string> urls) { foreach (var url in urls) AddStyleIfNotAlreadyPresent(url); }
And this to the user control base code-behind
private SiteMaster siteMaster { get { var master = Page.Master; if (master == null) return null; SiteMaster sm = master as SiteMaster; while (sm == null) { master = master.Master; if (master == null) return null; sm = master as SiteMaster; } return sm; } } protected void RegisterScript(string scriptUrl) { if (siteMaster != null) siteMaster.AddScriptIfNotAlreadyPresent(scriptUrl); } protected void RegisterScripts(List<string> scriptUrls) { if (siteMaster != null) siteMaster.AddScriptsIfNotAlreadyPresent(scriptUrls); } protected void RegisterStyle(string styleUrl) { if (siteMaster != null) siteMaster.AddStyleIfNotAlreadyPresent(styleUrl); } protected void RegisterStyles(List<string> styleUrls) { if (siteMaster != null) siteMaster.AddStylesIfNotAlreadyPresent(styleUrls); }
Every user control in the project can now register which JavaScript and CSS files it needs and the master page will know which files to serve to the client using SquishIt or whatever you want.