Monday, January 10, 2011

jQuery UI as AMD modules, for use in RequireJS

There was a request on the requirejs list for a conversion script that could convert jQuery UI files into a format more easily used by RequireJS. While it is possible to load custom builds of jQuery UI with RequireJS, having the jQuery UI scripts in AMD module format allows for flexible use:
  • Have the full range of jQuery UI available for use in different ways on different pages, but still get optimization benefits via the RequireJS optimizer.
  • Dynamically load parts of jQuery UI based on user actions.
The jQuery UI files already list their dependencies, but in a source comment. So it was fairly easy to whip up a command line utility (that is run via Node), to convert the files.

I created an example project too, showing how to load the Tabs widget, then when the user clicks on the second tab, dynamically load the Datepicker widget with its French localization.

The example project includes the RequireJS optimizer and a build profile. What is really neat: the unoptimized source project is about 25 HTTP requests. After the optimizer runs, it goes down to 8 requests, 4 of which are images.

There is more information on the conversion process in the README on GitHub. If the jQuery UI team is interested in supporting this more directly in their project, I'm happy to work with them to set up a define() stub/wrapper to allow the code to work even when an AMD loader like RequireJS is not in the page.

Enough talk, on the code:

4 comments:

TeMs@ said...

Good Job, it's really nice :)

Unknown said...

Your calls to define() include the "jqueryui" module which includes the
full jquery ui will all modules.

You shouldn't be required to include
the full jquery ui and only require
the modules that are actually required.

I think you could simply solve the problem by not
including "jqueryui" in your define()
calls.

James Burke said...

Ian Lewis: thanks for pointing out that unnecessary dependency. I have updated the project to remove that dependency, and to use jQuery UI 1.8.13 in the example.

Alfred said...

Great work. It would be useful to package for npm so that the 'compiler' can be put into a dependent project easily.