【问题标题】:Primefaces javascript defer parsingPrimefaces javascript延迟解析
【发布时间】:2013-12-29 04:20:42
【问题描述】:

从 PageSpeed Insights 可以看出,Primefaces 4.0 在页面加载期间会产生大量开销:

**605.3KiB of JavaScript is parsed during initial page load. Defer parsing JavaScript to reduce blocking of page rendering.**
http://localhost:8888/.../primefaces.js.xhtml?... (219.5KiB)
http://localhost:8888/.../jquery-plugins.js.xhtml?... (191.8KiB)
http://localhost:8888/.../jquery.js.xhtml?... (95.3KiB)
http://localhost:8888/.../tooltip.js.xhtml?... (34.5KiB)
http://localhost:8888/.../jsf.js.xhtml?... (25.4KiB)
http://localhost:8888/.../primefaces-extensions.js.xhtml?... (19.7KiB)
http://localhost:8888/.../watermark.js.xhtml?... (4.7KiB)
http://localhost:8888/.../hotkey.js.xhtml?... (1.2KiB)

知道如何将这些 3rd 方 javascript 文件设置在正文部分的底部,而不是 head 或使用 defer/async 参数吗? Javascript 加载器在这种情况下没有帮助,因为它们来自 JSF 渲染器。我还尝试为 PreRenderView (Best way for JSF to defer parsing of JavaScript?) 创建一个侦听器,但没有成功。还有其他可以解决这个问题的选择吗?感谢您的帮助!

【问题讨论】:

    标签: javascript jsf jsf-2 primefaces primefaces-extensions


    【解决方案1】:

    我得到了脚本的移动以使用以下 sn-p:

    public class ScriptValidateListener implements SystemEventListener {
    
        @Override
        public void processEvent(SystemEvent event) throws AbortProcessingException {
            UIViewRoot root = (UIViewRoot) event.getSource();
            FacesContext ctx = FacesContext.getCurrentInstance();
            List<UIComponent> resources = root.getComponentResources(ctx, "HEAD");
            for (UIComponent r : resources) {
                String name = (String) r.getAttributes().get("name");
                if (name == null) {
                    continue;
                }
    
                if (name.contains(".js")) {
                    root.removeComponentResource(ctx, r, "HEAD");
                    root.addComponentResource(ctx, r, "BODY");
                }
            }
        }
    
        @Override
        public boolean isListenerForSource(Object source) {
            return (source instanceof UIViewRoot);
        }
    }
    

    这会将所有 javascripts 从 HEAD 移动到 BODY 的末尾。但。 Primefaces 存在这个问题,呈现的组件将尝试访问 JQuery ($.) 或 PrimeFaces javascript 函数,这将破坏页面上的所有 ajax 功能。可能我需要决定哪些脚本要移动,哪些不能移动。也是监听器的一部分,我需要在 faces-config.xml 中定义以下内容以使其工作:

    <application>
        <system-event-listener>
            <system-event-listener-class>com.example.listener.ScriptValidateListener</system-event-listener-class>
            <system-event-class>javax.faces.event.PreRenderViewEvent</system-event-class>
        </system-event-listener>
    </application>
    

    【讨论】:

      猜你喜欢
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多