如何以编程的方式将JS和CSS资源添加到<h:head>中

8
我需要以编程方式向JSF页面的<h:head>添加JavaScript和CSS资源。但是不清楚该如何实现。我应该如何做或是否有一个示例代码?
2个回答

14

这要看你想在哪里声明资源。 通常情况下,编程声明它们的唯一原因是您有一个定制的 UIComponent 或者 Renderer,生成 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.StylesheetUIOutput,以分别表示完整的<h:outputScript><h:outputStylesheet>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");

1
在这里您可以找到有关声明放置位置的信息:https://dev59.com/clDTa4cB1Zd3GeqPGRYV - Thor
太好了!这救了我的一天。 - Dmitry Trifonov
我也在为在哪里添加声明而苦恼。最终,我将其添加到了我的UIComponent的构造函数中。 - Jasper de Vries
1
@JasperdeVries:在渲染响应之前调用的任何方法都足够了。在UIComponent内部,您通常会挂钩PostAddToViewEvent或者PreRenderViewEvent - BalusC

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);
}

1
虽然在JavaScript中使用这些是有效的,但在JSF上下文中并没有什么帮助。 - Jasper de Vries

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接