使用ClientDependency Framework动态添加CSS或JS的正确方法是什么?

时间:2016-10-24 21:11:17

标签: javascript c# css client-dependency

我很遗憾地说,但这里的文档有点缺乏:https://github.com/Shazwazza/ClientDependency/wiki/Webforms

我正在尝试动态注册依赖项,但无法正确使用语法:

<%@ 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>

文件HEAD:

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

我也尝试过使用它,但收到了错误:

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

而且,但是有一个不同的错误:

var loader = ClientDependencyLoader.GetInstance(currentHttpContext);

请帮助解释语法或指出正确的方向。谢谢!

1 个答案:

答案 0 :(得分:1)

这是我发现似乎有效的解决方案 - 我会在此处发布,以防其他人遇到类似情况:

对于CSS:

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

对于JS:

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

请注意,我并没有单独创建或引用现有的Loader,语法会处理它。

该解决方案改编自此页面上的代码:https://our.umbraco.org/forum/developers/razor/35307-Using-ClientDependency-Framework-from-a-Razor-Macro

希望这有助于某人!