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
       yuiloader.insert('js');
    
   ...

  


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.