【问题标题】:How to programmatically add JS and CSS resources to <h:head>如何以编程方式将 JS 和 CSS 资源添加到 <h:head>
【发布时间】:2012-09-09 04:55:33
【问题描述】:

我需要以编程方式将 JavaScript 和 CSS 资源添加到 JSF 页面的 &lt;h:head&gt;。目前尚不清楚如何实现这一目标。我该怎么做或有启动示例?

【问题讨论】:

    标签: javascript css jsf head


    【解决方案1】:

    您可以像这样向页面添加脚本和样式资源:

    var head = document.getElementsByTagName("head")[0];
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "xxxx.js";
    head.appendChild(s);
    
    s = document.createElement("style");
    s.type = "text/css"
    s.src = "yyy.css";
    head.appendChild(s);
    

    或者,以函数形式:

    function addScript(path) {
        var head = document.getElementsByTagName("head")[0];
        var s = document.createElement("script");
        s.type = "text/javascript";
        s.src = path;
        head.appendChild(s);
    }
    
    function addCSSFile(path) {
        var head = document.getElementsByTagName("head")[0];
        var s = document.createElement("style");
        s.type = "text/css";
        s.src = path;
        head.appendChild(s);
    }
    

    【讨论】:

    • 虽然这在 JavaScript 中使用时有效,但在 JSF 上下文中没有帮助。
    【解决方案2】:

    这取决于您要在哪里声明资源。 通常,以编程方式声明它们的唯一原因是您有一个自定义的UIComponentRenderer,它们生成的 HTML 代码又需要这些 JS 和/或 CSS 资源。然后由@ResourceDependency@ResourceDependencies 声明它们。

    @ResourceDependency(library="mylibrary", name="foo.css")
    public class FooComponentWithCSS extends UIComponentBase {
        // ...
    }
    
    @ResourceDependencies({
        @ResourceDependency(library="mylibrary", name="bar.css"),
        @ResourceDependency(library="mylibrary", name="bar.js")
    })
    public class BarComponentWithCSSandJS extends UIComponentBase {
        // ...
    }
    

    但是如果您真的需要在其他地方声明它们,例如在 渲染响应之前调用的支持 bean 方法中(否则为时已​​晚),那么您可以通过UIViewRoot#addComponentResource() 做到这一点。组件资源必须创建为具有javax.faces.resource.Scriptjavax.faces.resource.Stylesheet 渲染器类型的UIOutput,以分别代表一个完整的&lt;h:outputScript&gt;&lt;h:outputStylesheet&gt;libraryname 属性可以放在属性映射中。

    UIOutput css = new UIOutput();
    css.setRendererType("javax.faces.resource.Stylesheet");
    css.getAttributes().put("library", "mylibrary");
    css.getAttributes().put("name", "bar.css");
    
    UIOutput js = new UIOutput();
    js.setRendererType("javax.faces.resource.Script");
    js.getAttributes().put("library", "mylibrary");
    js.getAttributes().put("name", "bar.js");
    
    FacesContext context = FacesContext.getCurrentInstance();
    context.getViewRoot().addComponentResource(context, css, "head");
    context.getViewRoot().addComponentResource(context, js, "head");
    

    【讨论】:

    • 在这里您可以找到放置声明的信息:stackoverflow.com/questions/3586629
    • 太棒了!这节省了我的时间。
    • 我还在为在哪里添加声明而苦苦挣扎。我最终将它添加到我的 UIComponent 的构造函数中。
    • @JasperdeVries: before 渲染响应调用的任何方法都足够了。在UIComponent 中,您通常会挂上PostAddToViewEventPreRenderViewEvent
    猜你喜欢
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多