How to execute JavaScript after page load?

steffan picture steffan · Jan 25, 2012 · Viewed 53.8k times · Source

I would like to execute a JavaScript function after the page was loaded. At the moment I have a commandButton and everything works fine. However it would be more comfortable if the user is not supposed to hit the button.

I have tried f:event, but I do not have a listener, I have only the JavaScript function. Moreover body onload does not work for me as I use only high level components.

<f:view xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:pm="http://primefaces.org/mobile" contentType="text/html">

<ui:composition template="/resources/master.xhtml">

    <ui:define name="content">


        <pm:content>

            <h:inputHidden id="address" value="#{pathFinderBean.address}" />

            <div id="map" style="width: 100%; height: 285px;"></div>

             <p:commandButton type="button" value="Route" onclick="PathFinder.findAndGo()"/>

            <div id="route"></div>

        </pm:content>
    </ui:define>

</ui:composition>

The JavaScript function PathFinder.findAndGo is defined in my master.xhtml

Answer

Bhesh Gurung picture Bhesh Gurung · Jan 25, 2012

Use JQuery as follows:

<script>
    jQuery(document).ready(function() {
        PathFinder.findAndGo();
    });
</script>

Update:

It has to be within <ui:define name="content">.