Enhance the web page look & feel and behavior after it has been loaded - attach onLoad Event Listeners during load html

Enhance the web page look & feel and behavior after it has been loaded – attach onLoad Event Listeners during load

Many web applications are rendered by HTML rendering frameworks and technologies such as JSP, JSF, PHP, .NET etc. In such technology stacks, it is common to make use of standard components from 3rd party vendors and open source projects. Such components can typically be configured, customized to a certain extent. However, frequently there will be wish for more extensive customization and refinement, especially when it comes to look & feel in the browser.

Some simple examples:

  • rows in a table should be highlighted when hovered over
  • input items should be visually marked when entered by the user
  • items should be (slightly) repositioned or hidden
  • images, buttons or other elements should be added
  • event triggers should be added to for example perform client side validation or calculation
  • elements should be made draggable or set up as drop target
  • add background images to generated buttons

The list is long and restrained mainly by our own creativity and our project manager’s budget, the latter usually being the most restraining of the two.

While the rendering of the page can not always be effectively or efficiently influenced on the server – there is much we can do in the browser, using JavaScript and DOM Manipulation. However, for such manipulation to take place, the entire page has to be loaded first, otherwise there is no complete DOM model to access and manipulate. That means that many post-load actions should be started from the onLoad event. 

One way of making that happen is by adding an onLoad attribute to the BODY element of the HTML document and have it call all operations that we want to have performed after loading the page or calling a generic handler that knows which operations are registered to run once load is complete and will do so.

Since we want to limit the modifications to our (server side) page definitions and leverage standard browser functionality as much as possible, we can best achieve registering and executing post load operations without even touching the onLoad attribute itself – we will manipulate it indirectly.

Web browsers – at least of the two most recent generations – allow us to execute JavaScript snippets during the load of the page that register onLoad event listeners. These listeners will be called by the browser once the onLoad event occurs – when the page is completely loaded and ready for manipulation. The listeners are associated with JavaScript functions that will do their job.

Adding such JavaScript snippets to the page can be done by embedding the snippets in the page itself, either in the HEAD or in the BODY section. Alternatively, and often more efficient for generic post load operations, we can simply link a JavaScript library to our page and include the snippets in the JavaScript library.

Note: while the code presented in this article can be used, it is probably much wiser to leverage on of many JavaScript libraries out there to provide this ‘do after load’ operations for us. For example in jQuery – see: http://www.learningjquery.com/2006/09/introducing-document-ready – you can easily schedule actions to be performed after the page has loaded.

A simple example of such a Post Load operation – one that will do the immensely useful task of turning the text on all buttons to uppercase – is discussed next.

Post Load Example – set all button labels to uppercase

Create a JavaScript Library postload.js:

function addLoadListener(fn){
    if (typeof window.addEventListener !='undefined')    
      window.addEventListener('load',fn,false);
    else 
      if (typeof document.addEventListener !='undefined')    
        document.addEventListener('load',fn,false);
      else 
        if (typeof window.attachEvent !='undefined')    
          window.attachEvent('onload',fn);
        else {
          var oldfn=window.onload;
          if ( typeof window.onload !='function')    
            window.onload=fn;
          else    
            window.onload = function() { oldfn(); fn();}
        }
}//addLoadListener

function uppercaseButtonLabels() {
// find all buttons
var allBtn = document.getElementsByTagName(‘button’);
for(var n=0;n < allBtn.length;n++){
theBtn = allBtn[n];
// find the childnode of type text
if (theBtn.childNodes.length>0) {
for(var l=0;l < theBtn.childNodes.length;l++){
var child = theBtn.childNodes[l];
if (child.nodeType==3) // textnode
child.nodeValue= child.nodeValue.toUpperCase();
}// for button childnodes
}//if
}//for buttons
}//uppercaseButtonLabels

addLoadListener(uppercaseButtonLabels);

 

Assuming that postload.js is in directory public_html/js of my ADF Faces project, I can include the following link to the JavaScript library in my page definition:

      <afh:head title="#{nls['TABLE_TITLE_DEPT']}" id="head">
        <meta http-equiv="Content-Type"
              content="text/html; charset=utf-8"/>
        <script type="text/javascript" language="JavaScript"
                src="${pageContext.request.contextPath}/js/postload.js"></script>
      </afh:head>

Note: nothing is stopping me from adding page specific post-load operation through JS snippets in the JSF page like this:

        <f:verbatim>
          <script type="text/javascript" language="JavaScript">
                function postLoadGreeting() {
                  alert('Welcome on my page!');
                }

addLoadListener(postLoadGreeting);

</script>
</f:verbatim>

as long as it is within the body tag of the page.

One Response

  1. John Flack November 13, 2007