Yahoo! Developer Network Home - Help

YDN Site Search

# YUI Library Examples: YUI Loader Utility (beta): Using addModule to Add Custom (Non-YUI) Content with YUILoader

# YUI Loader Utility (beta): Using addModule to Add Custom (Non-YUI) Content with YUILoader

The YUILoader Utility is designed, of course, to help you put YUI components on the page. But your applications will frequently consist of a YUI-component foundation with your own application logic built on top. In other words, when you're loading YUI components you'll often want to load your own components as well.

This example shows you how to create a custom (non-YUI) module and load it via YUILoader. Click the "Load JSON" button below to load Douglas Crockford's JSON utility from JSON.org via YUILoader. Keep an eye on the Logger Control console at right to follow the logic as it executes after you click the button.

## Using `addModule` to Add Custom Modules via YUILoader

The purpose of this example is to illustrate one mechanism for adding custom (non-YUI) content to the page using the YUILoader Utility. For full documentation on this feature of the YUILoader, please refer to the "Using `addModule`" section of the YUILoader Utility User's Guide.

### Identifying an External Module to Load: The JSON Utility

Douglas Crockford, the inventor of JSON, has written a JSON Utility that helps you verify that information you've brought into the page as JSON is indeed limited to constructs that fit the JSON specification; this utility helps prevent some forms of malicious attacks embedded in JSON data from being successful in damaging you application or compromising its security.

In this example, we'll use YUILoader's `addModule` function to load the JSON Utility from `http://www.json.org/json.js`.

### Providing Load Verification for the External Component

First, we need to come up with a strategy for identifying when the external content is loaded. In the case of scripts that you write for use with YUI, we recommend you use the `YAHOO.register` method to register your component with the `YAHOO` global object once it's loaded (this is the mechanism that native YUI modules use). If you do that, YUILoader will be notified automatically when your custom module is loaded.

In this case, we are loading an external module that we don't control, so we need to write a `verifier` function that will determine for us when the JSON Utility has successfully loaded. That `verifier` method is passed a callback function for us to fire when it has successfully verified that the load is complete. Here's our `verifier` method for the JSON Utility, predicated on the fact that this utility makes a modification to the Object prototype — when that modification is there, we know the script has been loaded and processed. The `verifier` runs on a timer; it checks every 50ms until it verifies the load state of the JSON Utility:

//In this example, we're going to use a verifier //method that will verify when the added module is //completely loaded. The verifier is passed a callback //that it will fire to let YUILoader know that loading //is complete. Verifiers typically use a polling //mechanism to check for completeness. function checkJSON(name, loaderCallback) { YAHOO.log("Running verifier function to see if JSON Utility is loaded...", "info", "example"); //When the JSON utility is loaded, this will evaluate //to true: if (Object.prototype.toJSONString) { YAHOO.log("Verified! JSON Utility is loaded.", "info", "example"); loaderCallback(); } else { //not loaded yet; try again in 50ms YAHOO.log("Verifier determined that JSON Utility is not yet loaded; will try back in 50ms.", "info", "example"); setTimeout(function() { checkJSON(name, loaderCallback); }, 50); } }

### Invoke `addModule` to Make YUILoader Aware of the JSON Utility

Now that we have a `verifier` function, we're ready to tell YUILoader about the JSON Utility. This is a simple step in which we invoke `addModule` and pass in relevant metadata about our new module:

//Add the module to YUILoader loader.addModule({ name: "json", //module name; must be unique type: "js", //can be "js" or "css" fullpath: "http://www.json.org/json.js", //can use a path instead, extending base path verifier: checkJSON //the verifier function we just defined //requires: ['yahoo', 'event'] //if this module had dependencies, we could define here });

Note that in this case we're not setting up a dependency relationship between the JSON Utility and any other YUI components. However, in the commented-out last line above, we could use the `requires` member of the configuration object to make the JSON Utility depend on other YUI components or other custom components that we've defined.

### Full Source for This Example

The `addModule` and `verifier` steps are the most important elements of this example with respect to adding non-YUI content to the page via YUILoader. The full source of the example, including the use of the YUI Button Control to actuate the loading of the JSON Utility, follows here.

<!--Container for our call-to-action button--> <div id="jsonInsertButtonContainer"></div> <!--Container to which we'll append success message--> <div id="jsonContainer"></div> <script type="text/javascript"> //create our Button Instance which will trigger Loader to //load the JSON utility from json.org. YAHOO.example.buttoninit = function() { //Create the button instance: var oButton = new YAHOO.widget.Button({ id: "jsonInsertButton", type: "button", label: "Click here to load JSON Utility", container: "jsonInsertButtonContainer" }); YAHOO.log("Button created; click button to begin loading JSON.", "info", "example"); //Create a handler that handles the button click; //it logs the click, hides the button, then fires //the function (loaderinit) that brings in JSON: var onButtonClick = function() { YAHOO.log("Button clicked; hiding button now and loading JSON", "info", "example"); YAHOO.util.Dom.setStyle("jsonInsertButtonContainer", "display", "none"); YAHOO.example.loaderinit(); } //attach the handler to the Button's click event: oButton.on("click", onButtonClick); }; //Once the jsonInsertButtonContainer element is on the page, we can create //our button instance; in this case, the onContentReady deferral is unnecessary, //because we're writing the element to the page before this script, //but in many cases the onContentReady wrapper gives you added //flexibility and it comes at low expense: YAHOO.util.Event.onAvailable("jsonInsertButtonContainer", YAHOO.example.buttoninit); //Once JSON is loaded, we want to simply display a message that indicates //we were successful in bringing it into the page: YAHOO.example.onJsonLoad = function( ){ //Indicate on the page that the operation succeeded: YAHOO.util.Dom.get("jsonContainer").innerHTML = "The JSON utility was successfully loaded into the page. Scroll through the Logger Console output at right to review the timeline of steps that were followed by the script; note that most recent log messages appear at the top."; //Log the completion of the process: YAHOO.log("JSON utility was successfully loaded into the page, and the page was updated to indicate success. The process is complete.", "info", "example"); }; YAHOO.example.loaderinit = function() { YAHOO.log("YAHOO.example.loaderinit firing; we'll define our custom JSON module and load it now.", "info", "example"); //Begin by creating a new Loader instance: var loader = new YAHOO.util.YUILoader(); //In this example, we're going to use a verifier //method that will verify when the added module is //completely loaded. The verifier is passed a callback //that it will fire to let YUILoader know that loading //is complete. Verifiers typically use a polling //mechanism to check for completeness. function checkJSON(name, loaderCallback) { YAHOO.log("Running verifier function to see if JSON Utility is loaded...", "info", "example"); //When the JSON utility is loaded, this will evaluate //to true: if (Object.prototype.toJSONString) { YAHOO.log("Verified! JSON Utility is loaded.", "info", "example"); loaderCallback(); } else { //not loaded yet; try again in 50ms YAHOO.log("Verifier determined that JSON Utility is not yet loaded; will try back in 50ms.", "info", "example"); setTimeout(function() { checkJSON(name, loaderCallback); }, 50); } } //Add the module to YUILoader loader.addModule({ name: "json", //module name; must be unique type: "js", //can be "js" or "css" fullpath: "http://www.json.org/json.js", //can use a path instead, extending base path verifier: checkJSON //the verifier function we just defined //requires: ['yahoo', 'event'] //if this module had dependencies, we could define here }); loader.require("json"); //include the new module //Insert JSON utility on the page, passing in our callback: loader.insert(YAHOO.example.onJsonLoad); }; </script>

### YUI Logger Output:

### YUI Loader Utility (beta) Examples:

- Using YUI Loader to Load the Calendar Control
- Using YUI Loader to Place Additional Components on a Page
- Using addModule to Add Custom (Non-YUI) Content with YUILoader

### More YUI Loader Utility (beta) Resources:

- User's Guide (external)
- API Documentation
- Cheat Sheet PDF (external)

Copyright © 2007 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings