如何以编程方式在所有页面上加载JavaScript文件 [英] How to load a JavaScript file on all pages programmatically

查看:43
本文介绍了如何以编程方式在所有页面上加载JavaScript文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jsf jar库,我想在使用它的JSF 2.2项目的所有页面中加载一个特定的JavaScript文件(存在于jar中),而无需进行任何其他配置.

I have a jsf jar library, and I want to load a specific JavaScript file (exist in the jar) in all pages of the JSF 2.2 project that use it, and without any additional configuration.

我想加载库中存在的特定JavaScript文件而不使用 页面中的h:outputScript标签(模板和页面均不显示)

I want to load a specific JavaScript file exist in my library without use of h:outputScript tag in the page( Neither the template nor the page )

在jsf Web应用程序中有可能吗?

Is this possible in jsf web application?

推荐答案

您可以使用 SystemEventListener 上使用对于<h:head> PostAddToViewEvent 这个.

You can use UIViewRoot#addComponentResource() to programmatically add JSF resources. You can use a SystemEventListener on PostAddToViewEvent of <h:head> for this.

public class DynamicHeadResourceListener implements SystemEventListener {

    @Override
    public boolean isListenerForSource(Object source) {
        return "javax.faces.Head".equals(((UIComponent) source).getRendererType());
    }

    @Override
    public void processEvent(SystemEvent event) {
        String library = "yourLibraryName";
        String name = "yourScript.js"; // Can be dynamic here.
        addHeadResource(FacesContext.getCurrentInstance(), library, name);
    }

    private void addHeadResource(FacesContext context, String library, String name) {
        UIComponent resource = new UIOutput();
        resource.getAttributes().put("library", library);
        resource.getAttributes().put("name", name);
        resource.setRendererType(context.getApplication().getResourceHandler().getRendererTypeForResourceName(name));
        context.getViewRoot().addComponentResource(context, resource, "head");
    }
}

为了使其运行,请在模块项目的faces-config.xml中进行如下注册:

In order to get it to run, register it in faces-config.xml of your module project as below:

<system-event-listener>
    <system-event-listener-class>com.example.DynamicHeadResourceListener</system-event-listener-class>
    <system-event-class>javax.faces.event.PostAddToViewEvent</system-event-class>
    <source-class>javax.faces.component.UIOutput</source-class>
</system-event-listener>

这篇关于如何以编程方式在所有页面上加载JavaScript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆