Automatically Load JavaScript Files in PagePhaseListener
Hello.
In my application I want to load JavaScript files automatically on each page load or navigation. It can be done by using af:resource, but what I want that in my application I do not want to load each and every JavaScript files for every page. I needed an unification. So I have implemented a custom PagePhaseListener:
public class MHISPagePhaseListener implements PagePhaseListener {
public MHISPagePhaseListener() {
}
public void afterPhase(PagePhaseEvent pagePhaseEvent) {
}
public void beforePhase(PagePhaseEvent pagePhaseEvent) {
if (pagePhaseEvent.getPhaseId() == Lifecycle.INIT_CONTEXT_ID){
String function = "function loadJSFile(filename) {" +
"var headID = document.getElementsByTagName('head')[0];" +
"var newScript=document.createElement('script');" +
"newScript.type = 'text/javascript';" +
"newScript.src = filename;" +
"headID.appendChild(newScript);" +
"}" +
"loadJSFile('/hennessy/js/js/jquery-1.7.1.min.js');"+
"loadJSFile('/hennessy/js/document.ready.js');"+
"loadJSFile('/hennessy/js/jflow.plus.js');"+
"loadJSFile('/hennessy/js/ui/jquery.ui.core.min.js');"+
"loadJSFile('/hennessy/js/ui/jquery.ui.widget.min.js');"+
"loadJSFile('/hennessy/js/ui/jquery.ui.tabs.min.js');"+
"loadJSFile('/hennessy/js/ticker/jquery.ticker.js');";
FacesContext facesContext = FacesContext.getCurrentInstance();
ExtendedRenderKitService service = Service.getRenderKitService(facesContext, ExtendedRenderKitService.class);
service.addScript(facesContext, function);
}
}
}
Now when the page loads I can see all of these JavaScript files in HEAD, but my home page contains a TaskFlow and the view pagefragment of that TaskFlow contains $(document).ready(); and I get $ is not defined. That means the beforePhase() method is executing after the load of TaskFlow.
How can I solve this problem and how can I achieve this unification? Is there any way to register all JavaScript files globally?
Thank you.