【发布时间】:2012-09-09 04:55:33
【问题描述】:
我需要以编程方式将 JavaScript 和 CSS 资源添加到 JSF 页面的 <h:head>。目前尚不清楚如何实现这一目标。我该怎么做或有启动示例?
【问题讨论】:
标签: javascript css jsf head
我需要以编程方式将 JavaScript 和 CSS 资源添加到 JSF 页面的 <h:head>。目前尚不清楚如何实现这一目标。我该怎么做或有启动示例?
【问题讨论】:
标签: javascript css jsf 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 或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");
【讨论】:
UIComponent 中,您通常会挂上PostAddToViewEvent 或PreRenderViewEvent。