34,79 €
The YUI Library is a set of utilities and controls written in JavaScript for building Rich Internet Applications, across all major browsers and independently of any server technology. There's a lot of functionality baked into YUI, but getting to and understanding that functionality is not for the faint of heart. This book gives you a clear picture of YUI through a step-by-step approach, packed with lots of examples.YUI 2.8: Learning the Library covers all released (non-beta) components of the YUI 2.8 Library in detail with plenty of working examples, looking at the classes that make up each component and the properties and methods that can be used. It includes a series of practical examples to reinforce how each component should/can be used, showing its use to create complex, fully featured, cross-browser, Web 2.0 user interfaces. It has been updated from its first edition with the addition of several chapters covering several new controls and enriched with lots of experience of using them.You will learn to create a number of powerful JavaScript controls that can be used straightaway in your own applications. Besides giving you a deep understanding of the YUI library, this book will expand your knowledge of object-oriented JavaScript programming, as well as strengthen your understanding of the DOM and CSS. The final chapter describes many of the tools available to assist you the developer in debugging, maintaining, and ensuring the best quality in your code. In this new edition, all the examples have been updated to use the most recent coding practices and style and new ones added to cover newer components. Since the basic documentation for the library is available online, the focus is on providing insight and experience.The authors take the reader from beginner to advanced-level YUI usage and understanding.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 576
Veröffentlichungsjahr: 2010
Copyright © 2010 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: July 2010
Production Reference: 1080710
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-849510-70-7
www.packtpub.com
Cover Image by Gavin Doremus ( <[email protected]> )
Authors
Daniel Barreiro
Dan Wellman
Reviewers
Iliyan Peychev
Glenn Stephens
Acquisition Editor
Douglas Paterson
Development Editors
Ved Prakash Jha
Tarun Singh
Technical Editors
Kavita Iyer
Tariq Rakhange
Indexer
Hemangini Bari
Editorial Team Leader
Mithun Sehgal
Project Team Leader
Priya Mukherji
Project Coordinator
Vincila Colaco
Proofreader
Chris Smith
Production Coordinator
Arvindkumar Gupta
Cover Work
Arvindkumar Gupta
Daniel Barreiro (screen name Satyam) has been around for quite some time. The ENIAC was turned off the day before he was born, so he missed that—but he hasn't missed much since. He's had a chance to punch cards, program 6502 chips (remember the Apple II?), own a TRS-80, and see some fantastic pieces of operating equipment in his native Argentina, which might have been in museums elsewhere.
When globalization opened the doors to the world, his then barely usable English (plus an Electrical Engineering degree) put him on the career path that ended in a 5-year job in the Bay Area back in the days of NCSA Mosaic. Totally intrigued by the funny squiggles a friend of his wrote in his plain text editor, full of <'s and >'s, he ended up learning quite a lot about the world of frontend engineering.
It's been a long journey since COBOL and Fortran. Now he lives quite happily semi-retired in the Mediterranean coast close to Barcelona, Spain. When he's not basking in the Mediterranean sun, Satyam can be found among the most prolific and knowledgeable participants in the YUI community on the YUI developer forum. He has also authored the ProgressBar component and took over responsibility for the TreeView component of the YUI Library.
This book wouldn't exist had the guys in the YUI Team not done and continued doing such a magnificent work. Thanks to them for sharing their work with the community and for having invited me to participate; this has taught me lots about good programming practices.
Dan Wellman is an author and web developer from the UK. He works full-time for Design Haus, a local family-run digital agency, and specializes in creating fast, effective frontends using the latest technologies and solutions. In the evenings he writes books and tutorials on many aspects of web development, and spends time with his wife and four children. This is his fourth book.
Many thanks to Eamon O'Donoghue for the use of his stunning artwork that helped bring several of the examples in this book to life.
Iliyan Peychev is a Software Engineer with more than 10 years experience in different areas such as GPS tracking systems, map applications, security and Smart Cards, PKI, and X.509 Certificates. He started his career developing Win32 and GNU/Linux applications, then Java Enterprise Applications and now he is devoted to ECMAScript and Web developing. He has been using YUI library since 2006.
Iliyan has participated in many different projects concerning security, data control, and access to information. During the years he has developed many applications in multiple different areas—from a Java EE-based Smart Card management system to ECMAScript libraries like Windowing and SVG/VML drawing library, both built on top on YUI.
He spends his free time creating Open Source software. He has created some YUI Gallery modules like YUI Accordion.
At the moment, Iliyan is developing a large web-based system, which allows remote management and control of different kinds of devices, built on top of the YUI library.
Glenn Stephens is a developer, architect, and manager of software solutions and has been involved in numerous industries from education, security, finance and the health industry. Glenn has written numerous publications, has one Delphi/Kylix book under his belt and is the developer of the Monarch BPM Business Process Management software (www.monarchbpm.com). He is intrigued by many aspects of the software process such as architecture, operations and marketing, the roles of the user, and more. Glenn's weaknesses include all musical instruments, snowboarding and comedy clubs. Glenn can be contacted at <[email protected]>
He has also written the Tomes of Kylix—The Linux API many years ago (http://www.amazon.com/Tomes-Kylix-Linux-API-CD-ROM/dp/1556228236/ref=sr_1_1?ie=UTF8&s=books&qid=1273985360&sr=8-1).
The YUI Library has grown and improved since the first edition of this book. Several components came out of beta or experimental status and most of them will be covered in new chapters or added to related chapters, which will now have more than the two components originally presented.
The coding style has changed and that will be reflected in the examples, which have been modified accordingly.
New developer tools have appeared to make code more reliant, to reduce loading time, to debug, test, and do performance profiling and we will take a look at them.
The biggest change is the release of version 3 of the YUI Library. YUI3 has recently had its first General Availability (GA) release which includes the most basic components, the infrastructure of the whole library. The Widget component, the basis for all the components that will have a User Interface (UI) is still Beta so there are no visual components in GA. YUI3 still has some way to go to achieve the variety of UI components of YUI2 and, above all, the maturity and reliability of its code base. Thus, this book will be based on the current YUI 2.8 release of the library. YUI2 is not dead by any measure; development continues and future releases will come when and if any significant number of changes warrant it.
Loading YUI2 components in YUI3
JavaScript programming is not what it used to be. As we ventured into more complex client-side applications and learned more about the language and the environment it lives in, the programming style has changed. All the examples in the first edition of this book have been updated to the new coding style.
The components in the YUI Library show that same change in style, though some of the original ones now feel aged and the newer ones are more flexible and capable. However, for the sake of the innumerable applications out there, the old components cannot be upgraded as backward compatibility must be preserved. To get out of this tight spot, the YUI team decided to branch off with YUI3, incorporating all the techniques learned over these years. However, YUI3 is not backward compatible with YUI2. Version 2 of the library will still be maintained and upgraded and, in fact, since the two versions branched, there have been as many releases in the YUI2 branch as in the YUI3 branch.
Although YUI3 is a much better programming environment than YUI2 and it has a more consistent and capable interface, it still lacks components such as "widgets", that is, those that have a visual interface. Recently, however, the YUI3 loader (and at this point it is not necessary to go deep into what the loader does) has been enabled to load YUI2 components as well. YUI2 can and regularly does coexist with other non-YUI library components and so does YUI3; there was no reason for them to not coexist with each other. Now, this has been made much easier with the ability of the YUI3 environment to load YUI2 components.
This means two things. First, YUI2 still has a long life. By ensuring that they can run in the YUI3 environment, we can mix and match both versions. All the complex visual components in YUI2 that had no equivalent yet in YUI3 can be used in the YUI3 environment. And second, it means that the YUI team can relax and take their time migrating the YUI2 components, ensuring that when they do get released as YUI3 native, they will be high quality, as per our expectations.
WAI-ARIA
The Web Accessibility Initiative's committee of the World Wide Web Consortium has developed the ARIA (Accessible Rich Internet Application) suite of documents to make the rich applications we can build with YUI accessible to people with disabilities. The degree of support for ARIA is not even across all YUI components. Only components with a visual interface the visitor can interact with need ARIA support. Of those, most YUI components do support ARIA—some have it built-in, others need extra subcomponents, and some do not support ARIA at all. Those that do support ARIA often have a few configuration options, though the defaults rarely need any change. In other words, we as programmers usually don't need to concern ourselves with ARIA besides loading the required subcomponents, if any. We won't cover WAI-ARIA in this book just as we don't cover "beta" components, they are both a work-in-progress with its state still changing and, even when it is available, we rarely need to concern ourselves with it beyond activating it.
In Chapter 1, Getting Started with YUI, we look at the library as a whole covering subjects such as how it can be obtained, how it can be used, its structure and composition, and the license it has been released under. We also look at a coding example featuring the Calendar control.
In Chapter 2, Creating Consistency with the CSS Tools, we cover the extensive CSS tools that come with the library, specifically the Reset and Base Tools, the Fonts Tool, and the extremely capable Grids Tool. Examples on the use of each tool are covered. We also see how skinning works in the YUI Library.
In Chapter 3, DOM Manipulation and Event Handling, we look at the all-important DOM and Event utilities. These two comprehensive utilities can often form the backbone of any modern web application and are described in detail. We look at the differences between traditional and YUI methods of DOM manipulation and how the Event Utility unites the conflicting Event models of different browsers. Examples in this chapter include how the basic functions of the DOM Utility are used. We also look at the Element Utility, which is the basis of most of the new UI components and any a developer might build.
In Chapter 4, Calling Back Home, client-server communication is the subject, where we look at how the Connection Manager handles all of our XHR requirements. Then we look at the JSON data interchange format, which is becoming a popular alternative to XML, and at the Get Utility, which allows us to break out of the same-origin policy that limits XHR. Examples include obtaining remote data from external domains and the sending and receiving of data asynchronously to and from our own servers.
In Chapter 5, Animation, the Browser History Manager, and Cookies, we first look at how the Animation Utility can be used to add professional effects to your web pages. The chapter then moves on to cover how the Browser History Manager re-enables the back and forward buttons and book marking functionality of the browser when used with dynamic web applications. Finally, we take a brief look at the Cookies Utility, which allows us to persist information at the browser, helping us save user preferences across our site and in between visits.
In Chapter 6, Content Containers and Tabs, we look at the Container family of controls as well as the TabView control. Each member of the Container family is investigated and implemented in the coding examples. We also look at and implement the visually engaging and highly interactive TabView control.
In Chapter 7, Menus, we look at one of the most common parts of any website—the navigation structure. The example looks with the ease at which the Menu control can be implemented.
In Chapter 8, Buttons and Trees, the focus is on the Button family of controls and the TreeView control. We first cover each of the different buttons and look at examples of their use. We then implement a TreeView control and investigate the methods and properties made available by its classes.
In Chapter 9, DataSource and AutoComplete, we deal with the DataSource Utility, which allows us to fetch and parse tabular data from various sources, both local and remote and in various formats and deliver it to other components in a consistent manner. We will then look at one of those components, AutoComplete.
In Chapter 10, DataTable, we will see another user of DataSource, the DataTable control that allows us to display tabular information and efficiently operate on it on the client side with minimal server intervention.
In Chapter 11, Rich Text Editor, we see the Rich Text Editor, which allows our users to create enhanced text as one of the most popular forms of user interaction over the Internet is user-created content.
In Chapter 12, Drag-and-Drop with the YUI, the first part is Drag-and-Drop, one of DHTML's crowning achievements wrapped up in an easy-to-use utility. In the second part of this chapter we look at the related Slider control and how this basic but useful control can be added to pages with ease. We also briefly mention the Resizer and Layout components that allow us to move and resize dynamic panels within the browser.
In Chapter 13, Everyday Tools, we cover several developer tools. We see how the Logger Control is used to view the event execution of other controls and how it can be used to debug existing controls and custom classes. We also look at other resources such as JSLint and the YUI Compressor. We briefly mention other more advanced tools such as YUI Test, Performance Analyzer, and YSlow.
This book expects and requires you to have a prior knowledge and understanding of at least JavaScript, HTML, and CSS. While the use of the utilities, controls, and CSS tools will be explained in detail throughout the book, any HTML, CSS, or PHP code that is featured in any of the examples may not be explained in detail. Other skills, such as the ability to install and configure a web server, are required. A PC or Mac, a browser, text editor, the YUI, and a web server are also required.
This book is for web developers comfortable with JavaScript and CSS, who want to use the YUI Library to easily put together rich, responsive web interfaces. No knowledge of the YUI Library is presumed.
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: "In a capable, supported browser the library can transform the <textarea> element into the full Rich Text Editor control."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "The Collapse button will reduce it to the title bar itself".
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book on, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code for the book
You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
Welcome to the first chapter of YUI 2.8: Learning the Library. Throughout this book, we'll be exploring what makes up the library and what it can do for you. By implementing a selection of the available utilities and controls, we can see exactly how each one works and what functionality and tools it leaves at your disposal.
In this chapter we're going to introduce ourselves to the library by taking an overall view of it. The topics that we are going to cover include:
We'll also go over a brief coding example where you will get down to some proper scripting and find out for yourself just how easy it is to get up and running with the components themselves. This is where you will see the power provided by the library at first-hand.
The Yahoo! User Interface (YUI) Library is a free collection of utilities and controls, written primarily in JavaScript, which has been produced by the expert developers at Yahoo! to make your life easier as a web developer or frontend user interface designer.
It consists of a series of JavaScript and CSS components that can be used to quickly and easily build the rich and highly interactive applications that today's web consumer expects and demands.
The premise of the library is simple; often when writing JavaScript, you'll come up with a function that works perfectly in one browser, yet badly (or worse, not at all) in alternative browsers. This means that you'll often need a set of different functions to do exactly the same thing in different browsers.
This can be done for some of the major browsers without too much difficulty using standard object detection methods within if statements. However, this can lead to massively increased script files and unwieldy code that takes longer to debug and troubleshoot, and longer to write in the first place.
The YUI wraps both sets of code up into one object that can be used programmatically with one class, so instead of dealing with different sets of code for different browsers, you deal with the library and it makes the different calls depending on the browser in use.
Another important aspect of the library that I should mention at this point is its respect for the Global Namespace. All objects created by the library and its entire code run within, and can only be accessed through, the YAHOO Global Namespace object. This means that the entire library, including every utility and every control, and its numerous classes, create just one namespace object within the Global Namespace.
The Global Namespace is the global collection of JavaScript object names, and it is very easy to litter it with potentially conflicting objects, which can become a problem when code is shared between applications. The YUI library minimizes its impact on the Global Namespace while at the same time remains globally accessible by occupying a single name, YAHOO. However, for application code sandboxing is preferred and we shall show both techniques and mostly use the latter.
Essentially, the YUI is a toolkit packed full of powerful objects that enables rapid frontend GUI design for richly interactive web-based applications. The utilities provide an advanced layer of functionality and logic to your applications, while the controls are attractive pre-packed objects that we can drop onto a page and begin using with little customization.
The YUI is aimed at and can be used by just about anyone and everyone, from single site hobbyists to creators of the biggest and best web applications around. Developers of any caliber can use as much or as little of it as they like to improve their site and to help with debugging.
It's simple enough to use for those of you that have just a rudimentary working knowledge of JavaScript and the associated web design technologies, but powerful and robust enough to satisfy the needs of the most aspiring and demanding developers amongst you.
The library will be of interest primarily to frontend developers, as the main aim of the YUI is to provide a framework within which robust and attractive interfaces can be quickly and easily designed and built. It can help you to side-step what can otherwise be insurmountable compatibility issues.
There is no set standard that says you must know this much or that much before you can begin to use the YUI. However, the more you know and understand about JavaScript, the more the library will make sense to you and the more you will be able to gain from using it.
Trying to learn how to make use of the YUI without first knowing about the JavaScript language itself, at least to a basic working standard, is an endeavor likely to end in frustration and disappointment. It would be a great shame if a lack of understanding prevented you from enjoying the benefits that using the library can bring to both your creativity and creations.
So to get the most out of the YUI, you do need to have at least a basic understanding of JavaScript and the principles of object oriented programming. However, a basic working understanding is all that is required and those developers who have less knowledge of scripting will undoubtedly find that they come out of the experience of developing with the YUI knowing a whole lot more than they did to begin with.
The YUI can teach you advanced JavaScript scripting methods, coding, and security best practices, and more efficient ways of doing what you want to do. It will even help more advanced programmers streamline their code and dramatically reduce their development time, so everyone can get something from it.
For some, the YUI is also a challenge; it's an excellent opportunity for developers to get involved in a growing community that is creating something inspiring. The Firefox browser is a great example of an open source, community-driven, collaborative effort of separate but like-minded individuals. Some people may not want to develop web pages or web applications using the library: they may just want to be involved in evolving it to an even greater accomplishment.
I should also point out at this stage that like the library itself, this book expects you to have a prior knowledge and understanding of JavaScript, HTML, and CSS. While the use of the utilities, controls, and CSS tools will be explained in detail throughout the book, any HTML, CSS, or PHP code that is featured in any of the examples may not be explained in detail. Other skills, such as the ability to install and configure a web server, are also required.
Using any JavaScript library can save you great amounts of time and frustration when coding by hand, and can allow you to implement features that you may not have the knowledge or skill to make use of. But why should you use the YUI rather than the many other libraries available?
To start with, as I'm sure you already know, Yahoo! is extremely well established, and at the forefront of cutting-edge web technology and frontend design principles. The utilities and controls provided by the library have already been tried and tested in their world-class service provision environment. Hence you know that the components are going to work, and work in the way that you expect them to work and that Yahoo! says that they will. The YUI Library is not a second-rate product, it is what Yahoo! uses.
The YUI library is not the only developer-centric offering to come from these world-class leaders and to achieve high levels of accomplishment and a following amongst developers. Apart from this, other very successful projects include the extensive Design Pattern library, Yahoo! Widgets, and the Yahoo! Query Language. They also have a wide range of APIs for you to experiment and work with, so they have already shown a commitment to providing open source tools designed to succeed.
Additionally, the library has already been publicly available for over three years and in this time has undergone rapid and extensive improvement in the form of bug fixes and additional functionality. Like the Mozilla and Firefox browsers, it has a huge, world-wide following of developers, all seeking to further enhance and improve it.
Other libraries seek to alter the JavaScript language itself, by building capabilities into the language that the developers felt should already have been present and extending the language in new and interesting ways. While these libraries can provide additional functionality at a deeper and more integrated level, their use can often be hampered by technical implementation difficulties. These will be too difficult to overcome for all but the most advanced and seasoned developers.
The YUI is not like this; it is extremely well documented, stuffed full of examples, and is extremely easy to use. It doesn't get bogged down in trying to alter the JavaScript language at a fundamental level, and instead sits on top of it as a complementary extension.
There's also no reason why you can't use the YUI library in conjunction with other JavaScript libraries if a particular feature, such as the rounding of box corners as provided by MochiKit for example, is required in your application but not provided by the YUI.
Whichever browser you prefer, there's one thing that I think we can all agree on; all browsers are not created equal. Differing support and a lack of common standards implementation are things that have confounded web developers for as long as there have been web developers.
Although the situation is improving with agreed standards from the W3C, and we have better and more consistent support for these standards, yet we are far from being in a position where we can write a bit of code and know that it is going to function on any of the many browsers in use.
There may never come a time when this can be said by developers, but with the YUI, you can already count on the fact that the most popular browsers in use, on all types of operating systems, are going to be able to take full advantage of the features and functionality you wish to implement.
It doesn't, and can't be expected to support every single web browser that exists, but it does group together common browsers with common capabilities into a graded support framework that provides as much as it can to visitors no matter which browser they happen to be using.
Every single browser in existence falls into one of the defined grades; the most common class of browser are the A-grade variety of browsers, which the creators of the library actively support. These are modern, generally standards compliant and are capable of rendering in full the enhanced visual fidelity, and advanced interface functionality provided by the library as well as the inner core of content.
Though the number of browsers in this category is small, more than 95% of users regularly accessing Yahoo's sites use one of these. The YUI development team continually checks Yahoo's own statistics so that new browsers may be incorporated into or dropped from this category accordingly.
C-grade browsers are able to access the base or core content and functionality of the library components, but cannot handle the enhanced content. They are basically old, less capable versions of current browsers, or discontinued ones. These are browsers that are simply not supported by the library.
X-grade browsers are the ones that do not fall in the previous two categories. They are most likely to provide the full, enhanced experience. The most frequent cause for a browser to be in the X-grade list is that it does not have enough market share to justify devoting much time to test the YUI on it. A current example is Safari, which works fine in Windows, but it is not tested because it is an uncommon combination. Any browser that has not been extensively tested by the YUI development team is automatically an X-grade browser regardless of its capabilities.
Currently (in 2010 Q1), the complete spectrum of A-grade browsers supported by the library includes the following combinations of browser and platform configurations:
Browsers
Platforms
IE6, IE7, and IE8
Windows XP
IE8
Windows Vista
Firefox 3.0
Windows XP
Firefox 3.6
Windows XP, Vista and Mac OS 10.6
Safari 4.0
Mac OS 10.5 and 10.6
Google Chrome 4.0
Windows XP
These common configurations are able to make use of not just the core content of any applications we create with the YUI, but also all of the enhanced functionality brought on by the library. Any browser not on this list will still receive either an A or C-grade experience, but may be classed as an X-grade browser if it has not been extensively tested.
The graded browser support strategy is based on the notion of progressive enhancement as opposed to graceful degradation. Graceful degradation is a term that I'm sure you've heard at some point and involves designing content such that when it breaks in older browsers, it retains some semblance of order.
This method involves designing a page with presentation in your supported browsers as your main priority while still allowing unsupported browsers to view at least some kind of representation of your content.
Progressive enhancement approaches the problem of supporting browsers with different capabilities from the other direction by providing a core of accessible content and then building successive layers of presentation and enhanced functionality on top of this inner core of generalized support.
The following screenshot shows how the Rich Text Editor control appears in a C-grade browser. Older readers may recognize the browser used in this experiment as Netscape Navigator version 4—a browser popular approximately a decade ago.
As you can see from this example, the inner core of the page content is a standard HTML <textarea> element, which is displayed completely normally. The page doesn't break, but the high-fidelity content is not displayed. Using graceful degradation techniques, the browser would probably attempt to display the editor, but it would probably look very poor and would certainly not function.
The following screenshot shows how the editor appears in an A-grade browser:
In a capable, supported browser the library can transform the <textarea> element into the full Rich Text Editor control. Now the following screenshot shows exactly the same page in exactly the same browser but with JavaScript switched off:
Notice the similarity between a C-grade browser and an A-grade browser with JavaScript switched off.
The knowledge that has enabled Yahoo! to use the concept of graded browser support has been gained from the wide variety of user agents that hit their site every single day. They've been accessed by over 10,000 different software and platform configurations since they began focusing on by whom and how their portal is accessed. Approximately 96% of this total has received an A-grade experience when using the Yahoo! site.
Some JavaScript libraries are condensed into a single script file, such as the jQuery library. While this can make linking to them easier, it can be inefficient depending on how much of the library you actually use.
The YUI Library is split into its constituent components, making it easy to pick and mix which utilities and controls are used, and making it much more efficient to implement. In addition to the large collection of JavaScript files the library provides a great deal more.
The library is currently divided into four distinct sections; the library core files, a series of utilities, a set of controls, and some excellent CSS tools. These are complemented by a series of tools that assist in the development process. There are also three versions of most of the library's utilities and controls, including a full version of the underlying JavaScript file that powers each component, complete with whitespace and comments for better readability and understanding that can help your learning and development.
Along with the full versions, there are also -min.js and -debug.js versions of all the utilities and controls. The -min (for minified) files have had all whitespace and comments removed, and variable names have been shortened where possible to cut down drastically on file size. The tool used to produce the -min version, the YUI Compressor is available for downloading at the YUI site so you can use it on your own pages.
The -min versions of each component are perfect for production-release applications. These are the ones that you would include in your own pages. Once all development and testing is done, you should minify your own code. Your development code should be well commented and nicely formatted and spaced; you shouldn't scrimp on the code you write for the sake of reducing the file size, the YUI Compressor can take care of doing that for you.
The -debug version of each component is designed to be used in conjunction with the Logger Control rather than presented to your visitors. Along with whitespace and comments, these files also contain additional code that logs messages to the Logger console during key interactions within the components. In fact, the -debug version is the original source; the other two are automatically generated from this one by first stripping the logging messages for the full version and then compress for the minified one.
The differences between the full and -min versions of each file can be quite large, with the -min versions often being less than half the size of the full version. The only comment in each of the -min files is the copyright notice, which has to stay intact in every file. Other than that, these files are pretty much solid chunks of hard code and readability is therefore very poor.
To further improve the loading time of the library, several combinations of files often used together are provided as aggregates. Thus the core files can be loaded in just one go. These are provided only in minified form even though they lack the -min suffix.
Once the application is ready to be deployed, Yahoo provides two more performance enhancements. You may load the library files from your own servers, but you can also load them either from Yahoo's Content Delivery Network (CDN) or from Google's CDN. These ensure that the user of your application, anywhere in the world, can retrieve the YUI components from the closest server farm available, the very same servers that the Yahoo! site pages use.
Finally, Yahoo's CDN accepts combination requests. Browsers can only have a certain number of active communications channels open at once. When there are more requests for included files than it can handle, the rest will be queued. A combination request is one where the names of several components are concatenated into the same URL and requested all at once, thus avoiding getting later requests delayed in the queue.
If we try to load the Calendar component as well as the Base CSS Tools, this is how it translates into actual numbers:
Method
Number of connections
Download Size (KB)
Delay (ms)
Raw
9
93.9
2365
Minified
9
34.2
1662
Aggregates
5
33.1
1277
Combo
2
32.1
115
Combination requests are different from aggregate files. The latter are produced in the build process of the library and are available from both CDNs as well as in the developer download. The combination requests are completely dynamic and have to be produced on the fly with an application running on the CDN; the combined components do not exist as files in the CDN as the aggregates do. You cannot do a combination request from Google CDN nor when developing in your own machine. However, a first beta release of the application that serves these requests has been released as the YUI PHP Loader and an external contributor has already done an experimental port to Java.
To assist the developer in building the <script> and <style> tags required to retrieve the library components, the YUI site provides the Dependency Configurator. It lets you select the components you need, the version (-debug, full, or -min) you want, and which CDN you want to download it from. It will produce a listing that you can simply copy and paste into your page. All mandatory dependencies will be there in the proper order.
There are also three different file designations that each component can be classed as; fully released components are termed GA (General Availability). GA components are typically the oldest, have been tested extensively, and had most of the bugs weeded out. They are reliable and have been considerably refined.
Beta designated utilities and controls are still in the process of being ironed out, but they have been released to the development community for wider testing, bug highlighting, and feature suggestion.
Any component termed experimental is still in the conceptual phase of its design and may or may not be promoted to Beta or GA status.
The core of the library consists of the following three files:
The Global Object sets up the Global YUI namespace and provides other core services to the rest of the utilities and controls. It's the foundational base of the library and is a dependency for all other library components (except for the CSS tools). It also contains the YAHOO.Lang object which is made of a series of static methods that add functionality that the language, JavaScript, should have, such as a .trim() function for strings.
The Dom utilities provides a series of convenient methods that make working with the Document Object Model much easier and quicker. It adds useful selection tools, such as those for obtaining elements based on their class instead of an ID, and smoothes out the inconsistencies between different browsers to make interacting with the DOM programmatically a much more agreeable experience.
The Event Utility provides a unified event model that co-exists peacefully with all of the A-grade browsers in use today and offers a consistent method of accessing the event object. Most of the other utilities and controls also rely heavily upon the Event Utility to function correctly.
As the core files are required in most YUI implementations, they have been aggregated into a single file: yahoo-dom-event.js. Using this one file instead of three individual files helps to minimize the number of HTTP requests that are made by your application.
The utilities provide you with different sets of user-interface functionality that you can implement within your web pages. They provide programming logic and deal specifically with the behavior and interactions between your visitors and the different objects and elements on your pages.
They are a concept that you begin with and then build upon, and they provide the foundation from which you create your vision. They provide unseen behavior; for example, the Animation Utility isn't something your visitors will see directly, but its effects on the element being animated will of course be visible. They are the backstage hands of your application.
Like the core files of the library, several utilities have all been rolled up into one easy-to-link-to aggregate file: utilities.js. Again, this can be used to make your application run more efficiently when using all of the utilities together. The Dependency Configurator will automatically offer to load this file instead of its individual components if it proves smaller.
The set of utilities included in the current release of the library (which is constantly changing and growing) are as follows:
The Connection Manager is provided in the minimal, core, and the full featured version. So, if you need the very basic set of features, you are not loading the extras. Likewise, the basic Event Utility, part of the core utilities, is supplemented by an extra set of optionals. This pattern is repeated, as we will see in the next section.
The controls, on the other hand, are a collection of pre-packaged objects that can be placed directly on the page as they are, with very little customization. Your visitors can then interact with them.
These are objects on the page that have properties that you can adjust and control, and are the cornerstone of any web-based user interface.
These controls will be highly recognizable to most visitors to your site and will require little or no learning in order to use. The complete suite of controls currently included with the library is:
The CSS Tools form the smallest, but by no means the least useful, component of the library. The utilities and controls are designed to be used almost independently (although some of the files do depend on other files in the library to function properly), but the CSS tools are designed to be used together (although they can also be used separately if desired) and provide a framework for standardizing the visual representation of elements on the page.
The following four tools make up the current CSS section of the library:
The CSS tools have just two versions of each CSS file instead of three: a full version and a minimum version; there are no debug versions in this section of the library. As with the yahoo-dom-event utility, some of the CSS files have also been combined into one file for your convenience. You can use reset-fonts-grids.css or reset-fonts.css depending on your requirements.
These files are meant to assist you in the process of developing or deploying the application; they are not expected to ever reach the final user. They are:
The first four are JavaScript files that can be loaded along with your application to test or evaluate it. The others are external utilities written in different languages that need to be installed into your development machine or deployment server. These and other utilities developed by others will be covered towards the end of this book.
Once the library has been unpacked, you'll see that there are a series of folders within it; the build folder contains production-ready code that you can use immediately on your website. This is where the code that makes each component work and all of its associated resources, such as images and stylesheets can be found.
The docs directory contains the complete API documentation for every library component. This is where you can find the classes that make up each component, look at the underlying code, and review the properties and methods available to you.
The examples folder contains a series of demonstrative web pages that highlight the key functionality or behavior of each library component and mirror the example space found online. They are often a good place to start testing a new idea: find an example close to what you want and start changing it.
The tests folder contains a series of pages that use the YUI Test tool and the Logger Control to check that each component is functioning correctly for the platform on which it is being run. Each method for the component being tested is called, and the results are logged for you to examine. Any change or patch to the library should be tested to ensure it doesn't break existing functionality. These are the very same tests run on all A-grade browsers at Yahoo! before any new release.
The assets folder contains extras used either by the examples, the API docs, or index files in the library pack; they are not used by the YUI components. Finally, an as-docs folder contains the documentation for the interface to the SWF flash components, which are beta at this stage.
Another set of folders that you'll need frequently when using the library controls are the assets folders under each of the component folders in the build directory. Each of the controls has its own assets folder, which contains things like supporting images and stylesheets, as well as the sam skin files (if applicable) for display purposes.
There are some other files and folders within the library, such as an index for the library so that you can easily look for documentation or examples and release notes.
Due to the changing nature of the beta, and the experimental utilities and controls, we will not be looking at them in any great detail in this book. For information regarding any of these components, see the YUI site and API guides.
There are some additional resources that are available courtesy of Yahoo! to help you use the library to its maximum potential. There is a series of very helpful "Cheat Sheets" for each component at its developer guide page in a PDF file, which can be printed each on a single page.
These resources provide a useful and centralized reference manual, which lists the key methods, properties, and syntax patterns of each of the fully released components and gives some basic examples of their implementation.
There is a discussion forum, which developers can use to discuss their projects and get help from experts. The old Yahoo! Group for YUI developers, with 13,600 members and an average of 1000 messages a month until half a year ago, is still active but it has been steadily declining since then in favor of the new forum at http://yuilibrary.com/forum/. Both are fully searchable and they are a good place to start if you've got a problem with getting a utility or control to do what you want it to or to submit a question if there is no information listed.
The forum is home to a growing community of developers that have been brought together by the YUI; community involvement is an excellent way to connect with developers and can take a project in new and impressive directions.
For those of you who want to join the YUI development community and give something back to the Yahoo! Developers who have bestowed this awesome tool upon us, besides helping your fellow developers in the forum, there is also the facility to submit bug reports or feature requests. This is an excellent channel of feedback and as the YUI team points out, many useful features have been added to the library following a feature request. It also allows the team to remove errors and refine the features of existing components.
To file a ticket for a bug fix or an enhancement suggestion you can go to http://yuilibrary.com/projects/yui2/newticket. A year ago this tracking system resided in SourceForge.net, but it didn't have all the features the YUI team needed and, in fact, internally they used another system to track their progress so the two systems were often out of sync. Now, the bug tracker we see is the one the YUI team sees. Though all the members of the YUI team participate in the forum, if you find a bug don't just comment it in the forum, as forum posts cannot be tracked; the bug tracker is the place to ensure that a bug gets fixed.
Once a bug is fixed, you no longer need to wait until the next release to get your hands on the fix. The YUI Library and many of its tools are now saved into GitHub at http://github.com/yui so, as soon as you see a bug fixed, you can retrieve the latest build from the very same place the YUI team uses. This is a live development repository, so not all the files are in a stable state; any file retrieved from this repository has to be used with caution and generally not in a production environment.
To keep up-to-date on developments in the YUI and read associated news statements and technical articles about the library and the Yahoo! Developer Network in general, or to watch screencasts from the development team and other experts, you can visit the YUI blog at http://yuiblog.com.
This is a companion blog not just for the YUI Library but also for the Yahoo! Design Pattern Library. This is separate from the YUI and is not something that we'll be looking at in this book, but it is worth mentioning because the two resources can be used together in many situations.
The entire selection of different video screencasts and podcasts are brought together in one place for easy searching in the YUI Theater. Both the blog and the theater are subscribable via RSS, so that you can have up-to-date news and announcements surrounding the library.
Finally, you can go further: sign a Contributor License Agreement (CLA) and help with the YUI code itself. The CLA basically ensures that you agree to provide your contributions under the same license as the YUI and that you are not violating other people's rights when offering this code. This prevents any individual contributor from forcing exceptions to the general terms of the license used with the YUI.
All of the utilities, controls, and CSS resources that make up the YUI have been publicly released, completely for free, under the open source BSD license. This is a very unrestrictive license in general and is popular amongst the open source community.
For those of you who don't know anything about what the license stands for and what it allows you to do, I'll give you quick overview now so that you need not worry about it again. Consider these next few paragraphs your education in open source software licensing!
BSD stands for Berkeley Software Distribution and was originally designed and used by a team of developers who created an open source operating system of the same name that was similar in many ways to the UNIX platform (and even shared part of its code base with it). Many of today's most popular operating systems, including Windows and Mac OS X are derived from or contain code from the original BSD operating system.
The current BSD version, sometimes known as the New BSD license, differs from the original. It has had the restrictive UC Berkeley advertising clause removed, making it almost equivalent to the MIT license, but with the addition of a brief final clause prohibiting the use of the copyright owner's name for endorsement without obtaining prior consent.
