Run custom JavaScript when ADF page loads

Introduction

 

ADF is a complex framework which generates a number of components that are rendered dynamically via JavaScript. ADF also fires JavaScript when the page loads to initialize several components especially layout components.

Ideally you should avoid writing custom JavaScript in combination with ADF since it could get in way of ADF’s JavaScript. The problem becomes even more complicated when other JavaScript frameworks are involved such as jQuery. It is always preferred to use ADF JavaScript library for modifying components at run-time or responding to custom events. 

An excellent reference to get started with ADF JavaScript is presentation by ADF PM team: Using JavaScript in Oracle ADF Faces

Main Article

 

A common mistake is to use a JQuery code such as following for handling onLoad event. This may work in simple pages however its not guaranteed or supported in complex pages.

$(document).ready(function() {
  // Handler for .ready() called.
});

Worse, sometimes inline Javascript does not even get called resulting in a lot of confusion and number of debug hours.

Technique 1: Event queuing

The correct way to call a custom JavaScript when ADF page loads is to add to the onLoad event queue. This will make sure that ADF onLoad events are also called without interference.

 

  <af:resource type="javascript">
      //Script block 
      if (window.addEventListener) {
          /* Modern  browsers */
          window.addEventListener("load", onLoad, false)
      }
      else if (window.attachEvent) {
          /* IE */
          window.detachEvent("onload", onLoad)
          window.attachEvent("onload", onLoad)
      }
      else {
          window.onload = onLoad
      }
      function onLoad() {
          alert("I am running !");
      }
    </af:resource>

Webcenter Documentation Reference

 

Technique 2: The Preferred way

ADF does provide a number of hooks for Javascript such as onUnloadStandard Events and Custom Events. A similar hook is provided for capturing onload event.

     <af:document id="d1">

      <af:clientListener method="onPageLoad" type="load"/>
      <f:facet name="metaContainer">
        <af:resource type="javascript">
          function onPageLoad(evt) {
            alert("Hello");
          }
        </af:resource>
      </f:facet>
    </af:document>

Comments

  1. Hi Husain,

    Thanks for inputs.

    I have been trying to call js method on page load of a page fragment.

    I have followed your approach and its seems to be not working as expected.

    Could you please suggest.

    Thanks,
    Vamsi.

Add Your Comment