In some cases, you may wish to use YUI Loader to bring additional components into a page that already contains some YUI content. In this example, we'll look at how to use YUI Loader to augment a page's existing YUI content by bringing in additional dependencies for a new component.
The current page — the YUI examples template — uses several YUI components: The Logger Control to power the logger console in the upper right corner, the Button Control to stylize our "call-to-action" buttons for launching new windows or enabling the Logger, and so on. When you click the button in the middle of the example canvas below, YUI Loader will be used to fetch an additional component, the TabView Control, and construct a tabset in the example canvas. Watch the logger console at right to see the event flow as you push the button.
Our task here is to use the YUI Loader Utility to introduce a new YUI component, the TabView Control, onto a page that already has some YUI content loaded on it (in this case, the Button Control and the Logger Control). This pattern is one that can be useful any time you want to perform on-demand loading — loading of components only when their need is actuated by a specific user behavior.
Our "user behavior" in this example will be the click of a YUI Button. That button, when clicked, should disappear and give way to a TabView instance that we'll construct on the fly. Before we construct it, though, we'll have to load TabView onto the page; it's not loaded as part of the initial page load.
Our markup is simple: An element for our button and an element into which we'll place our TabView DOM structure once it's created:
Next, we instantiate our Button. This step consists of (a) creating the Button Instance and (b) assigning a click handler to execute our logic to load TabView and create a TabView instance when the button is clicked:
When the button is clicked, we first need to use YUI Loader to bring TabView onto the page. We've encapsulated that logic in
YAHOO.example.loaderinit, which in the code above we've tied to the button's click event. Here are the commented contents of the
loaderinit function in which we instantiate Loader, configure it, and then use its insert method to bring the TabView script and CSS dependencies into the page. Note: In this example we've loaded YUI Loader in the initial page load, so its functionality is available to us in our scripts.
We have configured Loader to call
YAHOO.example.tabviewinit when it completes its loading of TabView and its dependencies. Loader dutifully does this, waiting for each required module to load and then executing our code to setup our TabView instance. That last piece of the puzzle looks like this:
All YUI 2.x users should review the YUI 2.8.2 security bulletin, which discusses a vulnerability present in YUI 2.4.0-2.8.1.