Christian Heilmann

Dynamically including YUI components with YAHOO_config

Monday, September 3rd, 2007 at 11:53 am

One of my favourite tricks in scripting is to delay things until they are absolutely necessary to make sure that no user needs to deal with lot of code that doesn’t make sense to have at that point in time. This leads to faster pages and just makes sense. The most common trick for this is to add JavaScript library files using dynamically created script tags. I have already written about this in 2005 on this blog and it still is a cool thing to do.

The only problem I am seeing with this is that you never know when the other script has been loaded and it is safe to access the methods and variables in it. There are several ways to have a “loading ready” indicator but the browser differences are annoying : Jan Wolter has written about this in large detail.

The safest option is to write your scripts that get loaded dynamically to do a function call or amend an object once they are executed. However, sometimes you want to call library code that is not yours. Some APIs like the flickr or ones work around that by offering a callback parameter or wrap the returned dataset in a function. Not all third party code does that though.

One sensible solution for dynamic inclusion is YUI if you don’t want to have all the widgets you need later on loaded when they are not yet needed. The Rolls Royce solution for that is using the YUI Loader which even allows you to load non-YUI content on the fly. If you don’t want to go that far you can however have a poor man’s version of loader by observing the loading of components with YUI_config.

In order to do this you simply define a YAHOO_config object and point its listener property to your monitoring function. This has to happen BEFORE you insert the YUI YAHOO object!

The info parameter gets sent every time a new component of the YUI is loaded and ready to go. It is an object with several useful properties, the most useful ones being version and name of the YUI component. That way you can write different listener functions that get triggered when a certain component is available using the component names available on the YUI loader page. For example to only include animation on the fly and call an animation method once it is loaded you can use:

This is a very easy way to make sure you can use YUI components before you try to access them.

Share on Mastodon (needs instance)

Share on Twitter

My other work: