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

Posted

技术标签:

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

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

【问题讨论】:

【参考方案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");

【讨论】:

在这里您可以找到放置声明的信息:***.com/questions/3586629 太棒了!这节省了我的时间。 我还在为在哪里添加声明而苦苦挣扎。我最终将它添加到我的 UIComponent 的构造函数中。 @JasperdeVries: before 渲染响应调用的任何方法都足够了。在UIComponent 中,您通常会挂上PostAddToViewEventPreRenderViewEvent

以上是关于如何以编程方式将 JS 和 CSS 资源添加到 <h:head>的主要内容,如果未能解决你的问题,请参考以下文章

以编程方式添加 ODR 资源

以编程方式加载嵌入式资源文件

是否可以在资源管理器窗口中以编程方式将文件夹添加到 Windows 10 快速访问面板?

以编程方式将代码添加到javascript函数

如何以编程方式将 UIPageController 和 UICollectionViewController 添加到 UIViewController

如何以编程方式添加 Vue 3 组件?