jQuery and YUI 3: A Tale of Two JavaScript Libraries

By Mark RallOctober 27th, 2010

Recently I had the opportunity to build my first JavaScript front end application. What follows is a short story of the discovery and evolution that comes about when trying to use tools that aren’t suited for the job at hand. It is an account of the learning acquired through developing the same front end application using two very different libraries, jQuery and YUI 3. Details of the client and the project have been intentionally omitted.

Overview

The project involved the refactoring of several disparate Flash tools into a single interactive application based on open standards for a large content publisher. Of high importance, the application had to be highly optimised with a small initial foot print due the large number of daily page impressions the client receives. Several phases were involved, with the first being an initial proof of concept.

The concept involved the development of one view of what would be the completed application. It consisted of:

  • An initial seed file (< 1KB) responsible for the dynamic loading of any frameworks (e.g., jQuery or YUI 3) and the initial application file.
  • The development and inclusion of jQuery plugins to support form element styling and validation, and dynamic chart visualisations.
  • The generation and population of UI, based on user inputs, configuration defaults and the application’s location within the publisher’s site.
  • The calculation and presentation of information based on the user’s input.

In the interest of full disclosure, my own experience up to this point had been in developing small, standalone solutions, the type of which you could typically describe as plugins. These included dynamic UI components such as image carousels, interactive maps and Twitter / Flickr widgets. At the time of first dabbling with JavaScript, jQuery was popular, easy to learn and allowed me to quickly pick up the basics needed for the projects I was working on. However these were all standalone units and had no need to interact with other code or as part of a larger application.

First Attempt

On completing the first phase of the project, it became painfully obvious that I was dealing with a very different beast than what I was used to. Having had little experience in code organisation, my code quickly became disorganised, inefficient and repetitive. As a result, the first part of what would become a much larger application was slow to load. In fact it took eight seconds to generate that single proof of concept. A big change was needed and while I had considered using a small library like Dean Edward’s Base or John Resig’s Simple JavaScript Inheritance pattern to add class-based inheritance to jQuery, I decided to go one step further.

What I wanted was a complete, mature framework within which to develop my first OO application. Something that would effectively guide me through the process. In reviewing the available libraries I decided to adopt YUI 3 for the following reasons:

Take Two

Integrating YUI 3 brought several direct and indirect benefits to the project:

  • Inheritance-based architecture and class management through the Attribute interface, and Base and Widget classes producing performant, reusable and organised code.
  • Separation of presentation from model and data using the Widget class to render alternate views (inline or overlay) based on the application’s location within the site.
  • Sandboxing and dynamic module inclusion through YUI.use().
  • Cross-browser console debugging using YUI Console.
  • On save, performance optimisation using YUI Compressor in Eclipse.
  • Easy inclusion and integration of pre-existing jQuery plugins.
  • On save, automated code documentation using YUIDoc.

The final result was a happy client and a finished product with sub-second load times (remembering it took 8 seconds to load the initial proof of concept).

Lessons Learned

Select the right tool for the job

In reading this post I’m sure some readers will view this as anti-jQuery. Not at all. jQuery is a fantastic project responsible for many innovations. But, as with any tool, it has its strengths and an intended purpose. Its strength lies in normalising browser inconsistencies, lowering the barrier to entry for the novice and improving the efficiency of experienced programmers. The primary learning that came out of the project was that you can’t rely on one tool for every job. YUI builds on what jQuery can provide by also offering a well architected application framework. But it’s fair to say that it comes at a cost, see the next point.

Steep learning curve

You need patience, especially when writing your very first application with an unfamiliar library as I did. However the payoff is immense. By learning another library, not only will your core JavaScript skills improve, you’ll also develop a deeper understanding of how libraries work and the benefits they bring. I try to learn something new about YUI everyday and the more I learn, the more I’m in awe of the thought and sheer talent that’s gone into building YUI.

Only load content when you need it

While it’s certainly programmatically easier to just to load everything you may need upfront, the performance improvements gained as a direct result of lazy loading content only when you need it is huge. This was one of the key contributing factors for drastically improving the performance of the application.

Interact with the DOM as little as possible

This point doesn’t relate to the specific library used. By caching the required DOM elements and utilising HTML templates more, UI rendering time fell considerably. Nodes can be cached using Y.one() while node lists can be captured using Y.all(). Also Y.Node.create() was very useful in efficiently converting large text strings of HTML to DOM elements prior to insertion.

Learn by example, use a CDN

In using YUI’s CDN delivered library we decided to deliver all the project’s assets via CDN. This was probably the next largest contributing factor to the performance improvement.

Pub, sub hubbub

For those experienced programmers out there, try not to laugh at this one. Having been used to writing little more than plugins in the past, I had no idea how applications should communicate internally. Even after reading “Custom Events allow you to publish the interesting moments or events in your own code so that other components on the page can subscribe to those events and respond to them,” I still missed it.

As it turns out, YUI’s custom event publish-and-subscribe model works beautifully for inter-class and inter-object communication. You can even subscribe pre and post to events and include dynamic logic to suppress bubbling based on certain conditions.

Integrate best practice into your workflow

Using Eclipse we were able to integrate JSLint and YUI Compressor into the build process. Put simply, every time you hit Ctrl / Cmd + S your JavaScript code is validated and optimised. That means you’re testing against optimised, production grade code from the very first line of code. It also means that you won’t forget to optimise in the frantic final race to the delivery deadline.

Learning YUI on the Job

Although everyone has a different learning style, I thought I’d share what resources I used to learn YUI with a specific objective in mind.

Conclusion

YUI 3 is a full-featured, mature and constantly evolving library suitable for small to large projects. As front end web applications become more complex, the need for libraries like YUI will grow. While for the uninitiated it can be a daunting experience at first, if you stick with it you will be rewarded.

About the Author: Mark is a Senior Front End Developer at VI, a multi-disciplinary communications agency established in 1981 with a design orientation. Today the agency fuses its work in digital, direct and design disciplines to deliver measurable outcomes for a broad range of B2C and B2B clients.

5 Comments

  1. Jeffrey Gilbert said:
    October 27, 2010 at 6:22 pm

    So, as someone who has used YUI before currently uses jQuery a lot too, I don’t see this as a dig at jQuery. I also don’t see this as a well founded reason to use YUI over anything else. Lazy loading I definitely understand. A steep learning curve is not a plus. Since it’s pointed out in comparison to jQuery, google also offers a hosted CDN of jQuery builds. Event handling with custom events is an ECMAScript language based thing not specific to YUI. You can author any libraries code in Eclipse and still use Compressor or minifier to take it down in size.

    I’m glad you had success with YUI. It was my first library and I have a soft spot for all the documentation and published research Yahoo has created to help advance the knowledge of JS rookies everywhere.

  2. @Jeffery Gilbert

    Many thanks for your feedback. I’m not sure if you were after a response but here goes anyway…

    I don’t see this as a well founded reason to use YUI over anything else“. It wasn’t my intention. I merely wanted share the experience I had in building my first web app with jQuery and how I came to use YUI instead. As the disclaimer for most financial products goes ‘Consider your own individual circumstances before…’. For me at the time, it was the breadth of tools available, the level of documentation and most importantly the application framework. Of course it may not suite others.

    steep learning curve is not a plus“. ‘Lessons learned’ was not intended to be a benefits list. In the interests of full disclosure I also wanted to point out some of the challenging aspects, not only to be fair to jQuery but also to those considering starting with YUI 3. The main point is to stick with it. I believe it’s made me a much better programmer.

    google also offers a hosted CDN of jQuery builds“. And YUI 2.8 incidentally. When comparing a locally hosted version of YUI vs Yahoo’s CDN the performance boost was significant. It highlighted for us just how important using a CDN is to overall performance. So much so in fact that we decided to serve ALL application assets via CDN giving us sub-second load times for a reasonably large payload. It’s a lesson learned not a justification for YUI.

    Event handling with custom events is an ECMAScript language“. Agreed, custom events are not peculiar to YUI. It is how they are integrated into the larger framework that easily allowed me to build class based applications. Since then I’ve learned a little about Node.js and other event based paradigms. It’s really opened my eyes to event based programming. Hopefully others may experience the same light bulb moment.

    You can author any libraries code in Eclipse and still use Compressor or minifier“. Yes you can. When assessing various tools/solutions for a project some of a developers decision making will be invariably commercially based. How can I build a quality product quickly? YUI and it’s parent YDN offer a wealth of information for those like me who are starting out in front end application development. Here was one library with a range of performance tools and documentation that allowed me to get up and running quickly. Since then I’ve also discovered Rockstarapps’ Workbench that also plugs into Eclipse and automates the optimisation process. So yes you can, but for me YUI was the quickest to implement with a minimum of fuss.

    I have a soft spot for all the documentation and published research Yahoo has created to help advance the knowledge of JS rookies everywhere“.Me too and I think you’re right, it will. Especially as demand for dynamic, feature rich front ends increases.

    Thanks again for your feedback. Hopefully I’ve been better able to clarify some of my original intent.

  3. We actually did the opposite to you. We started building a very complex application in YUI then moved to jQuery during a re-write. The main reason was due to coding style, we are a Ruby house and no one really clicked with the way YUI is coded. jQuery was a much better fit for us as it’s much more rubyish with it’s implementation style.

    I do often wish jQuery implemented more basic language extensions missing from core JS however.

  4. Totally agree. Your point about architecture, I completely understand, but suspect it’s lost on those who don’t use (or understand) SE design patterns like publisher/subscriber. YUI definitely raises the bar by bringing these into JS development. Is there anything else out there that has AttributeProvider (yui 2) – which btw, I was glad to see included as a core part of 3! Great work by the YUI engineers and great post!

  5. @Jamie Dyer

    Hey Jamie. You raise a really interesting point which has been around in my brain since I first read your comment this morning, staggering out of bed clutching my phone.

    Perhaps is has to do in part with time constraints often experienced as part of the project life cycle. Selecting the right tool ideally comes down to best fit and I think it’s safe to say that the desire for standards and optimisation are a given these days. So what are the other potential influencers?

    Time
    Not only the time it takes to learn a candidate framework once selected but also the selection or review process itself. From that standpoint jQuery has the edge. As the tagline goes “jQuery: The Write Less, Do More, JavaScript Library”. It may be a huge presumption on my part, but I think of jQuery as a designer’s or beginner’s library. It allows you to get up and running quickly on those basic tasks that enrich a UI fromm a designer’s perspective. It may include showing/hiding content, transitions, DOM manipulation, Ajax and more.

    Coding Style
    Thinking about it now, it seems obvious that a developer’s previous experience is also influential. As you pointed out, being a Ruby programmer seems to have influenced your decision making. And why not. It’s perfectly valid reasoning. Again it seems to come back to commercial decision making. We naturally levitate to those solutions that present the least the resistance.

    For my own part, not having had any previous experience with programming apart form two modules of Java at uni (college) I had to influences. I was focused on how to write classes, manage attributes and above all performance. Perhaps things would have been different I’d continued to dabble in PHP or Java.

    So the questions for me are:

    What did you use to handle application management?
    If you used external tools to enhance jQuery, what were the impacts on the project’s delivery?

    Thanks Jamie, great comment.