javascript – 如何以编程方式添加JS和CSS资源?

前端之家收集整理的这篇文章主要介绍了javascript – 如何以编程方式添加JS和CSS资源?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要以编程方式将JS和CSS资源添加到< h:head> JSF页面.目前尚不清楚如何实现这一目标.有人可以给出提示或启动示例吗?

解决方法

这取决于你想要声明资源的确切位置.通常,以编程方式声明它们的唯一原因是您有一个自定义 UIComponentRenderer,它生成HTML代码,而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()之前完成.组件资源必须创建为UIOutput,具有javax.faces.resource.Script或javax.faces.resource.Stylesheet的渲染器类型,用于表示完整的< h:outputScript>或< h:outputStylesheet>分别.库和名称属性只能放在属性映射中.

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");
原文链接:https://www.f2er.com/js/156337.html

猜你在找的JavaScript相关文章