Adding Javascript to an Application Module

There are numerous ways for an application module to reference javascript (or stylesheets).

Application Module delegate method

One delegate method (callback) in an application module is pageDidLoad(), which allows the module to update the page's characteristics after its instantiation. Typically, this mechanism is used to add javascript for scripts unique to that application module.

Partial Listing: BlogViewer.php

class BlogViewer
{
    function pageDidLoad($page)
    {
        $page->addJavascript('js/search.js');
        $page->addStylesheet('css/blog.css');
    }

}

The IWPage instance passed as an argument ($page) prefixes the addJavascript() argument with the APPL_LIB_DIR constant and adds it to the <head> tag of the rendered HTML page. Suppose you needed an external javascript file. In that case, there are two possible approaches, both illustrated below.

Partial Listing: MapViewer.php

class MapViewer
{
    function pageDidLoad($page)
    {
        $javascript = 'http://maps.google.com/maps/api/js?sensor=false';

        // Pass an IWURL object as the addJavascript() argument
        $page->addJavascript(new IWURL($javascript));

        // Directly update the head() element of the IWPage instance
        $page->head()->addExternalJavascript($javascript);
    }
}

Note that the same concept works for stylesheets, except the methods are addStylesheet() and addExternalStylesheet() instead.

Page initialization method

For javascript or stylesheets that are common to many application modules, I typically add them in the initialize method of the IWPage subclass used by the application module. For example, if I intended to use GoogleMaps in a number of application modules, I might apply the API javascript to a page shared by those modules.

Partial Listing: MapPage.php

class MapPage extends XHTML11Page
{
    function initialize()
    {
        // Add internal javascript
        $this->addJavascript('css/map.js');

        // Add the external javascript directly to the &lt;head&gt; element of the page
        $google = 'http://maps.google.com/maps/api/js?sensor=false';
        $this->head()->addExternalJavascript($google);
    }
}