Even Faster Web Sites Steve Souders Editor Andy Oram Copyright © 2009 Steve Souders O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. O’Reilly and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Even Faster Web Sites, the image of a blackbuck antelope, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. O'Reilly Media Credits Even Faster Web Sites contains six chapters contributed by the following authors. Dion Almaer is the cofounder of Ajaxian.com, the leading source of the Ajax community. For his day job, Dion coleads a new group at Mozilla focusing on developer tools for the Web, something he has been passionate about doing for years. He is excited for the opportunity, and he gets to work with Ben Galbraith, his partner in crime on Ajaxian and now at Mozilla. Dion has been writing web applications since Gopher, has been fortunate enough to speak around the world, has published many articles and a book, and, of course, covers life, the universe, and everything else on his blog at http://almaer.com/blog. Douglas Crockford was born in the wilds of Minnesota, but left when he was only six months old because it was just too damn cold. He turned his back on a promising career in television when he discovered computers. He has worked in learning systems, small business systems, office automation, games, interactive music, multimedia, location-based entertainment, social systems, and programming languages. He is the inventor of Tilton, the ugliest programming language that was not specifically designed to be an ugly programming language. He is best known for having discovered that there are good parts in JavaScript. This was an important and unexpected discovery. He discovered the JSON (JavaScript Object Notation) data interchange format. He is currently working on making the Web a secure and reliable software-delivery platform. He has his work cut out for him. Ben Galbraith is the codirector of developer tools at Mozilla and the cofounder of Ajaxian.com. Ben has long juggled interests in both business and tech, having written his first computer program at 6 years old, started his first business at 10, and entered the IT workforce at 12. He has delivered hundreds of technical presentations worldwide, produced several technical conferences, and coauthored more than a half-dozen books. He has enjoyed a variety of business and technical roles throughout his career, including CEO, CIO, CTO, and Chief Software Architect roles in medical, publishing, media, manufacturing, advertising, and software industries. He lives in Palo Alto, California with his wife and five children. Tony Gentilcore is a software engineer at Google. There, he has helped make the Google home and search results pages lightning fast. He finds that the days seem to fly by while writing web performance tools and techniques. Tony is also the creator of the popular Firefox extension, Fasterfox. Dylan Schiemann is CEO of SitePen and cofounder of the Dojo Toolkit, an open source JavaScript toolkit for rapidly building web sites and applications, and is an expert in the technologies and opportunities of the Open Web. Under his guidance, SitePen has grown from a small development firm to a leading provider of inventive tools, skilled software engineers, knowledgeable consulting services, and top-notch training and advice. Dylan’s commitment to R&D has enabled SitePen to be a major contributor to and creator of pioneering open source web development toolkits and frameworks such as Dojo, cometD, Direct Web Remoting (DWR), and Persevere. Prior to SitePen, Dylan developed web applications for companies such as Renkoo, Informatica, Security FrameWorks, and Vizional Technologies. He is a cofounder of Comet Daily, LLC, a board member at Dojo Foundation, and a member of the advisory board at Aptana. Dylan earned his master’s in physical chemistry from UCLA and his B.A. in mathematics from Whittier College. Stoyan Stefanov is a Yahoo! frontend developer, focusing on web application performance. He is also the architect of the performance extension YSlow 2.0 and cocreator of the Smush.it image optimization tool. Stoyan is a speaker, book author (Object-Oriented JavaScript from Packt Publishing), and blogger at http://phpied.com, http://jspatterns.com, and YUIblog. Nicole Sullivan is an evangelist, frontend performance consultant, and CSS Ninja. She started the Object-Oriented CSS open source project, which answers the question, How do you scale CSS for millions of visitors or thousands of pages? She also consulted with the W3C for their beta redesign, and she is the cocreator of Smush.it, an image optimization service in the cloud. She is passionate about CSS, web standards, and scalable frontend architecture for large commercial websites. Nicole speaks about performance at conferences around the world, most recently at The Ajax Experience, ParisWeb, and Web Directions North. She blogs at http://stubbornella.org. Nicholas C. Zakas is the author of Professional JavaScript for Web Developers, Second Edition (Wrox) and coauthor of Professional Ajax, Second Edition (Wrox). Nicholas is principal frontend engineer for the Yahoo! home page and is also a contributor to the Yahoo! User Interface (YUI) library. He blogs regularly at his site, http://www.nczonline.net. Preface Vigilant: alertly watchful, especially to avoid danger Anyone browsing this book—or its predecessor, High Performance Web Sites—understands the dangers of a slow web site: frustrated users, negative brand perception, increased operating expenses, and loss of revenue. We have to constantly work to make our web sites faster. As we make progress, we also lose ground. We have to be alert for the impact of each bug fix, new feature, and system upgrade on our web site’s speed. We have to be watchful, or the performance improvements made today can easily be lost tomorrow. We have to be vigilant. Vigil: watch kept on a festival eve According to the Latin root of vigil, our watch ends with celebration. Web sites can indeed be faster—dramatically so— and we can celebrate the outcome of our care and attention. It’s true! Making web sites faster is attainable. Some of the world’s most popular web sites have reduced their load times by 60% using the techniques described in this book. Smaller web properties benefit as well. Ultimately, users benefit. Vigilante: a self-appointed doer of justice It’s up to us as developers to guard our users’ interests. At your site, evangelize performance. Implement these techniques. Share this book with a coworker. Fight for a faster user experience. If your company doesn’t have someone focused on performance, appoint yourself to that role. Performance vigilante—I like the sound of that. How This Book Is Organized This book is a follow-up to my first book, High Performance Web Sites (O’Reilly). In that book, I lay out 14 rules for better web performance: Rule 1: Make Fewer HTTP Requests Rule 2: Use a Content Delivery Network Rule 3: Add an Expires Header Rule 4: Gzip Components Rule 5: Put Stylesheets at the Top Rule 6: Put Scripts at the Bottom Rule 7: Avoid CSS Expressions Rule 8: Make JavaScript and CSS External Rule 9: Reduce DNS Lookups Rule 10: Minify JavaScript Rule 11: Avoid Redirects Rule 12: Remove Duplicate Scripts Rule 13: Configure ETags Rule 14: Make Ajax Cacheable I call them “rules” because there is little ambiguity about their adoption. Consider these statistics for the top 10 U.S. web sites[1] for March 2007: Two sites used CSS sprites. 26% of resources had a future Expires header. Five sites compressed their HTML, JavaScript, and CSS. Four sites minified their JavaScript. The same statistics for April 2009 show that these rules are gaining traction: Nine sites use CSS sprites. 93% of resources have a future Expires header. Ten sites compress their HTML, JavaScript, and CSS. Nine sites minify their JavaScript. The rules from High Performance Web Sites still apply and are where most web companies should start. Progress is being made, but there’s still more work to be done on this initial set of rules. But the Web isn’t standing still, waiting for us to catch up. Although the 14 rules from High Performance Web Sites still apply, the growth in web page content and Web 2.0 applications introduces a new set of performance challenges. Even Faster Web Sites provides the best practices needed by developers to make these next-generation web sites faster. The chapters in this book are organized into three areas: JavaScript performance (Chapters 1–7), network performance (Chapters 8–12), and browser performance (Chapters 13 and 14). A roundup of the best tools for analyzing performance comes in the Appendix A. Six of the chapters were written by contributing authors: Chapter 1, Understanding Ajax Performance, by Douglas Crockford Chapter 2, Creating Responsive Web Applications, by Ben Galbraith and Dion Almaer Chapter 7, Writing Efficient JavaScript, by Nicholas C. Zakas Chapter 8, Scaling with Comet, by Dylan Schiemann Chapter 9, Going Beyond Gzipping, by Tony Gentilcore Chapter 10, Optimizing Images, by Stoyan Stefanov and Nicole Sullivan These authors are experts in each of these areas. I wanted you to hear from them directly, in their own voices. To help identify these chapters, the name(s) of the contributing author(s) are on the chapter’s opening page. JavaScript Performance In my work analyzing today’s web sites, I consistently see that JavaScript is the key to better-performing web applications, so I’ve started the book with these chapters. Douglas Crockford wrote Chapter 1, Understanding Ajax Performance. Doug describes how Ajax changes the way browsers and servers interact, and how web developers need to understand this new relationship to properly identify opportunities for improving performance. Chapter 2, Creating Responsive Web Applications, by Ben Galbraith and Dion Almaer, ties JavaScript performance back to what really matters: the user experience. Today’s web applications invoke complex functions at the click of a button and must be evaluated on the basis of what they’re forcing the browser to do. The web applications that succeed will be written by developers who understand the effects of their code on response time. I wrote the next four chapters. They focus on the mechanics of JavaScript—the best way to package it and load it, and where to insert it in your pages. Chapter 3, Splitting the Initial Payload, describes the situation facing many web applications today: a huge JavaScript download at the beginning of the page that blocks rendering as well as further downloads. The key is to break apart this monolithic JavaScript for more efficient loading. Chapters 4 and 5 go together. In today’s most popular browsers, external scripts block everything else in the page. Chapter 4, Loading Scripts Without Blocking, explains how to avoid these pitfalls when loading external scripts. Loading scripts asynchronously presents a challenge when inlined code depends on them. Luckily, there are several techniques for coupling inlined code with the asynchronous scripts on which they depend. These techniques are presented in Chapter 5, Coupling Asynchronous Scripts. Chapter 6, Positioning Inline Scripts, presents performance best practices that apply to inline scripts, especially the impact they have on blocking parallel downloads. I think of Chapter 7, Writing Efficient JavaScript, written by Nicholas C. Zakas, as the complement to Doug’s chapter (Chapter 1). Whereas Doug describes the Ajax landscape, Nicholas zooms in on several specific techniques for speeding up JavaScript. Network Performance Web applications aren’t desktop applications—they have to be downloaded over the Internet each time they are used. The adoption of Ajax has resulted in a new style of data communication between servers and clients. Some of the biggest opportunities for growth in the web industry are in emerging markets where Internet connectivity is a challenge, to put it mildly. All of these factors highlight the need for improved network performance. In Chapter 8, Scaling with Comet, Dylan Schiemann describes an architecture that goes beyond Ajax to provide high-volume, low-latency communication for real-time applications such as chat and document collaboration. Chapter 9, Going Beyond Gzipping, describes how turning on compression isn’t enough to guarantee optimal delivery of your web site’s content. Tony Gentilcore reveals a little-known phenomenon that severely hinders the network performance of 15% of the world’s Internet users.
Description: