Bogdan Bogdan - 1 month ago 7
Javascript Question

What is the proper way to dynamically add CSS or JS using ClientDependency Framework?

I'm sorry to say, but the documentation is somewhat lacking here: https://github.com/Shazwazza/ClientDependency/wiki/Webforms

I'm trying to register a dependency dynamically and cannot get the syntax right:

<%@ Page Language="C#" AutoEventWireup="false" %>
<%@ Register TagPrefix="CD" Namespace="ClientDependency.Core.Controls" Assembly="ClientDependency.Core" %>

<script runat="server">
protected override void OnLoad(EventArgs e)
{
if (Request.Cookies["AAPGmobile"] != null && Request.Cookies["AAPGmobile"].Value == "Mobile")
{
//mobile
ClientDependencyLoader.RegisterDependency("~/Style/mobile.css",ClientDependencyType.Css);
}
else
{
//desktop
ClientDependencyLoader.RegisterDependency("~/Style/desktop.css",ClientDependencyType.Css);
}
}
</script>


Document HEAD:

<CD:ClientDependencyLoader runat="server" id="Loader" />
<asp:PlaceHolder runat="server" ID="CssPlaceHolder"></asp:PlaceHolder>
<asp:PlaceHolder runat="server" ID="JavaScriptPlaceHolder"></asp:PlaceHolder>


I also tried using this, but got an error:

bool successfullyCreated;
var loader = ClientDependencyLoader.TryCreate(this.Page, out successfullyCreated);


And this, but got a different error:

var loader = ClientDependencyLoader.GetInstance(currentHttpContext);


Please help with the syntax or point me in the right direction. Thanks!

Answer

This is the solution I found that seems to work – I'm posting it here in case anyone else runs into a similar situation:

For CSS:

ClientDependencyLoader.Instance.RegisterDependency("~/Style/mobile.css",ClientDependency.Core.ClientDependencyType.Css);

For JS:

ClientDependencyLoader.Instance.RegisterDependency("~/Style/mobile.js",ClientDependency.Core.ClientDependencyType.Javascript);

Please notice, I'm not trying to create or reference an existing Loader separately, the syntax takes care of it.

The solution is adapted from code on this page: https://our.umbraco.org/forum/developers/razor/35307-Using-ClientDependency-Framework-from-a-Razor-Macro

Hope this helps somebody!