YUI PHP Loader Utility: Adding Custom (Non-YUI) Content with YUI PHP Loader

The YUI PHP Loader Utility is designed, of course, to help you put YUI components on the page. While the YUI PHP Loader is great at loading YUI resources it is important to point out that it can also be a great resource for loading custom non-YUI JavaScript and CSS resources on the page as well. These can be mixed in with YUI dependencies and/or be all custom modules.

This example shows you how to create a set of custom (non-YUI) modules and load them via YUI PHP Loader.

Defining a Custom Module

The YAHOO_util_Loader class constructor accepts four parameters:

  1. yuiVersion: Version of YUI metadata to load
  2. cacheKey: Unique name to use as the APC cache key. Module calculations are cached for performance if the environment supports APC.
  3. modules: An array of custom modules
  4. noYUI: Enable or disable the base YUI metadata

The modules parameter expects an associative array. The array should consist of custom JavaScript and/or CSS modules. The modules array format mirrors that of the YUI metadata included with PHP Loader. Use the metadata in the lib/meta folder as a reference for determining all the possible options. Below is an example of such an array:

Note: The module names must be unique and should not conflict with any of the existing YUI component names if you have chosen to leave the YUI metadata enabled. To make a custom module dependent on an existing YUI module simply default a requires key/value pair that lists out the desired YUI components.

Simple Example with no YUI Dependencies

For this example we will load a remote JavaScript resource (i.e.) Douglas Crockford's JSON utility from JSON.org, some local JSON data, and a custom CSS module via the YUI PHP Loader Utility. When the document is loaded will process the JSON data with the JSON utility, create additional unordered list items with that data, and apply a CSS class to the last item which will use custom styles defined in our custom CSS module.

Here's what that looks like in terms of raw source — this is the full source code for this example:

This code executes the following steps in order:

  1. The YUI PHP Loader class is included
  2. A custom module set is defined
  3. An instance of YUI PHP Loader is created: Our custom module set is passed to the Loader
  4. YUI PHP Loader calculates the dependencies and order of our custom modules: The Loader knows our customJS module is dependent on our JSONModule module.
  5. YUI PHP Loader loads the modules and is used to output the CSS and JavaScript: The <link> nodes are output in the document head and the <script> nodes are output just before the closing body node. This is in accordance with the best practice performance recommendations outlined here.