Wednesday, October 7, 2009

YUI PHP Loader

YUI PHP Loader Home

I have made several PHP loaders for YUI over the years, and it's nice to see this library come about. Taking a look at the examples, I can see that I had the right idea. The PHP Loader is more robust and cleaner than my implementations however.

So, the problem this PHP code solves is loading your scripts or YUI scripts dynamically on page load without having to write any of the YUI loader script.

In my implementations, I setup arrays in php that would be converted to json with json_encode. The constructor would setup all the arguments, and delay the .insert() method so that it can be placed near the bottom of the page. The constructor would then generate the required JavaScript code to be output with a PHP call. This would in turn dynamically load all my scripts in a non-blocking manner. I would also setup my global namespace before the loader call and add any required variables I needed for that page in that namespace. So, and example in the PHP "view" of the constructor may look like

< ? php
$load_these = array('calendar', 'datatable', 'myCustomLib');
$loader = new YUILoader($load_these, array('config' => 'someConfigValue'));
? >

    < div id="footer">
    < script type="text/javascript">
        // Insert the scripts


Your PHP source could pull from a config file to populate the $load_these array, and in that manner you can dynamically set the JavaScript that was loaded on the page.

In the YUI PHP Loader, they have somewhat simplified the insert() calls in providing $loader->css() and $loader->script() methods to print the script I have above.

In the backend libraries that I have created, I have also added my own scripts that I wanted the YUILoader to know about. I accomplished this by setting up arrays in php to hold the information about the scripts the YUILoader expects (name, fullpath, requires array etc). The script then adds the addModule JavaScript code to the loading.

Something that the PHP Loader does that I have not added to my own modules is the combination handler. This is where the backend gathers up all the scripts that you want, and combines them into a single download. This dramtically improves page load performance, and saves bandwidth.

Other advantages to this is that the files are server locally, so your site does not have to rely on a 3rd party domain to serve the files. This is especially usefuly where SSL is required or where you can not use a remote server. This includes combining your own files along side YUI modules. To add your own modules, simply add them to the configuration files in lib/meta

You can also change the default skin in the configs. This comes in handy when your testing things and want to setup an override.

I really have been waiting for something like this, and I am glad it has come into being.

Monday, August 10, 2009

YUI Sparkline Widget « Chicken of the Web

YUI Sparkline Widget « Chicken of the Web

If your into cutting edge, this is a nice example of subclassing YUI 2.7 charts to create sparklines in <canvas> and javascript.

Blogged with the Flock Browser

Saturday, August 8, 2009

YUI 3: Design Goals and Architecture -Satyen Desai » Garuna Web Designer

YUI 3: Design Goals and Architecture -Satyen Desai » Garuna Web Designer

Satyen Desai goes over lessones learned from YUI 2.7, and the design goals for YUI3. YUI 2 users have expressed the need for more from YUI3

  1. Lighter
    1. Finer Granularity
    2. Code reuse, common base class, easier to create plugins and extensions
  2. Easier
    1. Conistant API
      1. Selector, Widget class, Base
    2. Convenience - each, bind, chaining, syntax sugar
  3. Faster
    1. Opportunity to re-factor performance (drag and drop etc)

These are all valid points. In YUI 2, if I want to use a specific util or widget, I would get alot of code that I really didn't need all the time. In YUI 3 you get the option to only include parts of the components you need. This makes sense when building plugins, and widgets of your own, as well as how the core objects relate. A Tooltip widget for instance does not need all the code for an Overlay or dialog box even though they may use some of the same code for making shims or floating elements.

Satyen also goes over application instances with YUI().use() and how it is protected, and self populating. For exmaple YUI().use("anim") will attach optimal dependencies for the anim library, and attach anim to Y. var $anim = new Y.Anim(). This version of anim is garunteed to be the version of the library you are working with, and will never conflict with other widgets on the page.

The custom event handling in YUI 3 has grown quite mature with Event Facades for Dom events and Custom events. 

Custom Events:

slider.on('valueChange', function(e){
  if(e.newVal < 200) {
     alert("New Value " + e.newVal + " is less than 200");

Over all this is a wonderful introduction in getting developers up to speed with the changes from YUI 2 to YUI 3.
Blogged with the Flock Browser

Friday, August 7, 2009

Using Prototype and YUI

Using prototype and YUI

There are many reasons why you might use prototype.js with yui. You may be moving to Yahoo User Interface, or vice versa, or you may just prefer some flexibility. Whatever the reason, there are some good points to using the two together. I have pointed out several times on this blog and Practical Prototype that I personally prefer this method. I use YUI for the widgets, and use prototype for setting up classes, events, and other low level organization. Let's see a quick example:

MySimpleDialog = Class.create({
  initialize: function($div_id, $options){
    this.defaults = {
      width: "20em",
      fixedcenter: true,
      visible: false,
      draggable: true
    Object.extend(this.defaults, $options || {});
    this.dialog = new YAHOO.widget.SimpleDialog($div_id, this.defaults);
  render: this.dialog.render,

  setTitle: function($title){ this.dialog.setHeader($title);}
  setBody: function($body){ this.dialog.setBody($body); }

To initialize a new MySimpleDialog all we have to do now is:

var $mydialog = new MySimpleDailog('my div id');

Notice we do not have to send any options to the SimpleDialog constructor, and if we had, they would override the defaults. To get Fancy, we could create a Template class to be used by our "overridden" setBody method. Keeping things generic helps you to reuse scripts.

Friday, July 24, 2009

Y.get() != new Element()

While trying to use YUI 3.0, I was attracted to try out the YUI Node feature with the following code

$ele = Y.get('foo');

I was working out some race condition problems, and was hoping the waiting feature (where YUI will wait for the element to be in a ready state) would solve some problems for me.

What I had forgot was that Y.get is not the standard dollar function ( $('foo'), $('#foo'), etc ). This poses some real problems for me. I didn't really used the Dom.get methods, and probably for the same reasons, as I use both YUI and prototype together mostly.

But now I want to integrate the really nice features of YUI 3 into my code, and try and break away from my prototype "crutch". However, since I do use other 3rd party libraries for various things, most of them rely on straight up Dom elements being passed to them.

I hate to say it, but I have found something in YUI that just does not sit well with me.

The code still seemed to work with

$ele = $('foo');

But I can't say for sure, and this seems pretty hacky?

Sunday, July 19, 2009

YUI 3.0.0 beta 1

YUI 3.0.0 beta 1 is now available for download from

From the Yahoo! User Interface Blog:

"This release takes YUI 3 out of its preview phase and brings its APIs to a near-final state. For those intending to implement YUI 3, the 3.0.0 beta 1 release is a good place to begin the transition. If you’ve been working with the latest preview release, George Puckett has provided a comprehensive 3.0.0 beta 1 changelog to guide you. We look forward to hearing your feedback as you begin working with 3.0.0 beta 1, and we’ll work hard to address that feedback as we prepare for a GA release in the coming months."

Some very interesting things made this release

"StyleSheet: StyleSheet makes it easy to create and modify CSS rules on the fly, allowing you to dynamically style page elements with fewer repaints."

Add stylesheets dynamically!

"ImageLoader: ImageLoader allows you to defer the loading of images that aren’t in the viewport when the page paints, throttling bandwidth usage and improving performance"

Images won't load until they enter the viewport, for longer pages, or hidden elements this is pretty huge. The bandwidth savings could be worth it.

Thursday, July 9, 2009

Technorati Code


Sunday, February 22, 2009

YUI 3 Preview Release 2 - IO

Today I will go over the new IO Utility in the YUI 3 Preview Release 2

"IO is an HTTP utility that enables HTTP requests while maintaining a persistent client UI, for the purpose of data retrieval and content update. IO uses the XMLHttpRequest object for making "same-domain" requests. IO can make "cross-domain" requests, when instructed to do so, using an alternate HTTP transport."

What does this mean really? This means we have a single, consistent, interface to various data sources we may point our UI at. This data may be from our site, or another data provider on a different site. When the data resides on our site IO will use XHR (XMLHttpRequest ) to request the data, standard "AJax". When we are making our request cross-domain, the IO utility will use a flash swf to make the call, along with a crossdomain.xml (to let the flash know which sites it has access to). The crossdomain.xml is fairly important on a https: site as IE will complain to no end that you are trying to access non secure data, or mixing secure with non-secure.  The crossdomain.xml resides in your document root.

So, let's see what the YUI 3 team has given us. The basic example provided at the IO Utility page sets up the use of io-base, defines a completed function, and subscribes to the event. The key here seems to be subscribing to the event :

// Subscribe to event "io:complete", and pass an array
// as an argument to the event handler "complete". Since
// "complete" is global.
// At this point in the transaction lifecycle, success or
// failure is not yet know.
Y.on('io:complete', complete, this, ['lorem', 'ipsum']);

When the event "complete" finishes, we want to run "complete" function with "this" as the context of execution, and pass also an array ['lorem', 'ipsum']

This may be quite different and confusing to just about every other Framework out there. But so much better! There are a few posts on nabble where people are asking why the IO isn't "seperate" for each request, and the answer lies above. IO is a presistant connection, and it has a context that it runs in. If you are specifying IO in the global context, then all your requests are going to be in the global context, which is specified by "this".

In other words, Event handlers run in thier own context, so you could have multiple listeners on the io:complete event, but only some would run depending on context:    Therefore, you could register a GlobalEvents object and set that context, just as in the examples and this would run for every IO request. If however, you have objects with different scopes, the global would fire as well as the callbacks in different scopes that are set to listen for io:complete.  

The new IO utility also offers a "queue" which you can start, stop, promote, purge, and set the size. This is a big step in ajax frameworks as most like prototype do not come with these capabilities built in. With a queue you can send transactions and gracefully monitor and manage them with the io events and queue commands.

One way I can see this being very useful is if you had created a queue on page onload to load various items not immediatly visible to the user. But say the user then clicks on one of the items, we can immediatly stop the queue, and promote that request to the top of the queue, and when that completes, continue with the loading of the rest of the items! This is, to say the lease, very useful.

Thursday, February 19, 2009

YUI 3 Preview Release 2 - Get Utility

Yahoo's User Interface Get Utility is one of my favorites. I use this constantly to load secondary scripts on the page, or when some event requires additional scripts. For example, while putting together a RIA with dialogs, you may not need the "container" library to load when the page loads, you may want to delay this till the user actually performs and action the requires the container to show.

// Code in main page

var $Y = YUI();
ele.on('click', function(){
$getScripts = $Y.Get.script('/js/myDialog.js', {
onSuccess: function(){
// I ran myDialog.js .. assume here that it render()s the dialog;
// Do other things


This is much unchanged from YUI 2.6, and if your upgrading from 2.6 you would find this an easy "fix" to port to YUI 3. Most likely you will also have your own alias variable and namespace you can integrate this into.

In the above code we are using $Y.Get.script to get a single script and load it. Usually with these files I will use the (function(){ ... })(); convention. This makes it a little more clear what the code will do. If I have created namespaces, I will give each file it's own namespace and use it throughout the file.

This does a couple things. If used on page load, the scripts will be retrieved in a non-blocking manner. In other words, your images and CSS will not be in contention with the loading of these scripts. You will also be able to delay the loading of some scripts until they are actually needed.

Some practical applications you could use this for possibly is loading the validation logic on form submit, loading dialogs, calendars, and any of the heavier widgets that are not visible on first load. 

Up Next :  IO

YUI Shed Presents - YUI 3.x Preview Release 2

    YUI 3.x has been brewing for some time now under the radar. I personally have kept peeking in to see if they had any of the widgets from YUI 2 working in this latest releases. As of YUI 3.x Preview Release 2 We have the first widgets, Overlay, Slider, and Console, along with MenuNav Nodes. This is a pretty big step forward, and gives me incentive to give each new component a test run, and provide a bit of practical use code. Over the next few days I will dive into each of the new components and give some use case code.

"Stay Tuned!"

Wednesday, February 11, 2009

Nicole Sullivan on YUI Theater

This was a very good installment of YUI theater, that all web developers should take a look at. Her talk goes into image sprites, things already recommended by YSlow!, and some very interesting points to consider when designing a website. Sometimes, a few bad requirements will make things difficult to maintain, as well as make for bad markup and or bad javascript.

If you have never visited YUI Theater, your in for a treat. I highly recommend *ALL* of the videos there. Crockford is "the man".

Friday, February 6, 2009

YUI and Google Gears Data Sets

I recently have had some requests to post some examples of how to use YUI with Google Gears. Below is the code for a simple example using the developer's example from Google Gears documentation as a starting guide.

var loader = new YAHOO.util.YUILoader({

require: ['json', 'datatable'],
onSuccess: function(){
var db = google.gears.factory.create('beta.database');'database-test');
db.execute('create table if not exists Test' +
' (Phrase text, Timestamp int)');
db.execute('insert into Test values (?, ?)', ['Monkey!', new Date().getTime()]);
var rs = db.execute('select * from Test order by Timestamp desc');

// Create an object to hold the Results
ResultSet = {rows: []};

var fieldCount = rs.fieldCount();
count = 0;

while (rs.isValidRow()) {
var tmp = {};
for (x = 0; x < fieldCount; x++) {
// Add Each field to tmp object
tmp[rs.fieldName(x)] = rs.field(x);
// Push object onto Results

// YUI DataSource
var dsLocalJSON = new YAHOO.util.LocalDataSource(ResultSet);
dsLocalJSON.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
/* Could also use rs.FieldName here to do dynamic */
dsLocalJSON.responseSchema = {
resultsList: "rows",
fields: ["Phrase", "Timestamp"],
meta: {
totalRecords: count

/* Colum Definitions */
var ColDefs = [{
key: 'Phrase',
label: "The Phrase"
}, {
key: 'Timestamp',
label: 'Epoch',
sortable: true

var DataTable = new YAHOO.widget.DataTable('datatable', ColDefs, dsLocalJSON);

You will of course have to add the proper CSS and JS include files. For this example I used the datatable.css in the sam skin directory, the gears_init.js and YUI Loader js file. You will also need a div with and id='datatable'.

This example will use the loader to get the datatable javascript, as well as the json library. You can use the json library to parse out the record rows you don't need with this.

Hope this helps some people!