我需要以编程方式向JSF页面的
<h:head>
添加JavaScript和CSS资源。但是不清楚该如何实现。我应该如何做或是否有一个示例代码?<h:head>
添加JavaScript和CSS资源。但是不清楚该如何实现。我应该如何做或是否有一个示例代码?这要看你想在哪里声明资源。 通常情况下,编程声明它们的唯一原因是您有一个定制的 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.Script
或javax.faces.resource.Stylesheet
的UIOutput
,以分别表示完整的<h:outputScript>
或<h:outputStylesheet>
。 library
和name
属性可以直接放在属性映射中。
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");
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);
}
UIComponent
内部,您通常会挂钩PostAddToViewEvent
或者PreRenderViewEvent
。 - BalusC