2013-12-11 66 views
1

Primefaces 4.0從PageSpeed Insights會看到正在產生大量的開銷在頁面加載過程:Primefaces JavaScript的推遲解析

**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) 

任何想法,JavaScript文件可以設置這些第三方如何在身體部分的底部而不是頭或使用延遲/異步參數?在這種情況下,Javascript加載器不起作用,因爲這些來自JSF渲染器。另外我試圖爲PreRenderView創建一個監聽器(Best way for JSF to defer parsing of JavaScript?),但那並不奏效。任何其他可以解決這個問題的選項?謝謝你的幫助!

回答

1

我拿到劇本的移動與followind片段的工作:

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); 
    } 
} 

這將所有的JavaScript從頭部到身體的末端。但。 Primefaces存在這樣的問題:所呈現的組件將嘗試訪問JQuery($。)或PrimeFaces JavaScript函數,並且會打破頁面上的所有ajax功能。顯然我需要決定要移動的腳本和不移動的腳本。另外一部分來自Listener,我需要將以下內容定義爲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>