In the modern Web interface development, inline event handlers considered as the bad practice – see article for detail.
Also, for performance reason, Web experts ( Yahoo YSlow, Google Page Speed and others ) recomend to load plain html code first, and only add user interaction code at the bottom of page.
jQuery library makes that stile pretty easy, using $(page).ready() or just $() callbacks. But, there is a problem with JSF AJAX: jQuery knows nothing about JSF library, and code inside page.ready handler will nether be called after page update.
How it works
Getting service instance:
The service instance created by RichFaces initialization listener, and can be replaced by different implementation by custom Module, see documentation for ServiceTracker.
Adding script to be rendered at the bottom of page:
What does this method do ? It looking for special UIScripts component in the UIViewRoot.componentResources collection, or creates new if there to such component yet, and append script object to the Set of objects submitted to be rendered. To avoid rendering of the same script more then once, it checks collection for the same script ( using equals() method ). If the same object already submitted to be rendered, it returns existing object. Otherwise, new script added to the collection and returned by method. That check allows to render the same script only once, even if component that requires such code rendered many times.
For example, component that wraps jQuery widget can use special ‘class’ attribute to mark its instance on the page, and the same script can activate all widgets using that class as discriminator.
Another method lets developer to append script that will be rendered inside page.ready handler:
content of the scripts collection goes here
See jQuery documentation for ready() function for details how it works.
For AJAX requests ( important note – only RichFaces AjaxBehavior supported ) the same scripts rendered in the <execute> part of response that processed after DOM updates. Therefore, the same code works for both page rendering and AJAX modes.
In addition, script object can implement org.richfaces.resource.ResourceLibrary interface and provide additional dependencies. These dependencies will be rendered as links to external resources before in-content <script> element.