Adding embedded resource with ClientDependency
The uComponents project for Umbraco is coming along rather nicely! So far there are 13 new data types created and a few extensions, hopefully soon we’ll have a package ready to go. In the meantime, I thought I’d share a nice little code snippet that we’re using this throughout uComponents that allows you to add embedded resources to ClientDependency. It’s pretty easy and works perfectly with Umbraco 4.5 or any other site you have running ClientDependency. This will ensure that embedded resources (JavaScript or CSS) are added to the ClientDependency combined scripts/styles and also compressed and cached.
First, I’ll show you how to register your embedded resources using our extension method class (for a Control object):
this.AddResourceToClientDependency(
"DataTypesForUmbraco.Controls.Shared.Resources.PrevalueEditor.css",
ClientDependency.Core.ClientDependencyType.Css);
The above code assumes:
- The class that you are consuming the code inherits from System.Web.UI.Control
- That your embedded resource’s path is: DataTypesForUmbraco.Controls.Shared.Resources.PrevalueEditor.css
- If you don’t know about embedded resources, or know how they work, you should read: Working With Embedded Resources in ASP.Net
- That your embedded resource is a CSS type
Pretty easy right!! Well, the only thing missing is that you’ll need to add our extension method class to your project which looks like this:
///
/// Extension methods for embedded resources
///
public static class ResourceExtensions
{
///
/// Adds an embedded resource to the ClientDependency output by name
///
///
///
///
public static void AddResourceToClientDependency(this Control ctl, string resourceName,
ClientDependencyType type)
{
//get the urls for the embedded resources
var resourceUrl = ctl.Page.ClientScript.GetWebResourceUrl(ctl.GetType(), resourceName);
//add the resources to client dependency
ClientDependencyLoader.Instance.RegisterDependency(resourceUrl, type);
}
///
/// Adds an embedded resource to the ClientDependency output by name and priority
///
///
///
///
public static void AddResourceToClientDependency(this Control ctl, string resourceName,
ClientDependencyType type, int priority)
{
//get the urls for the embedded resources
var resourceUrl = ctl.Page.ClientScript.GetWebResourceUrl(ctl.GetType(), resourceName);
//add the resources to client dependency
ClientDependencyLoader.Instance.RegisterDependency(priority, resourceUrl, type);
}
}
So basically, if you have a Control, you can register your embedded resources in ClientDependency with one line of code... sweeeeet.
Need an Umbraco Master?
Here at Simon Antony, we have an in house certified Umbraco Grand Master available for hire. Got a problem with your site, need architecture advice, give us a call to speak to Simon directly and see how we can help
Contact Simon Today!