Third-Party JavaScript
Ben Vinegar & Anton Kovalyov
Copyright
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact
Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 261 Shelter Island, NY 11964 Email:
orders@manning.com2013 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps.
Recognizing the importance of preserving what has been written, it is Mannings policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine.
| Manning Publications Co.20 Baldwin RoadPO Box 261Shelter Island, NY 11964 | Development editor: Renae GregoireTechnical proofreaders: Alex Sexton, John J. Ryan IIICopyeditor: Benjamin BergProofreader: Katie TennantTypesetter: Dottie MarsicoCover designer: Marija Tudor |
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 MAL 18 17 16 15 14 13
Brief Table of Contents
Table of Contents
Foreword
You, as a third-party JavaScript developer, have a multitude of concerns you need to manage to ship code across a number of sites and platform combinations. Never before have the details and best practices of making solid distributable JavaScript been codified in such depth as they are in this book. This can be a tricky business, so allow me to illustrate the potential for unintended consequences by telling you a story about Douglas Crockford, who created one of the most widely distributed third-party scripts, and a site called OnlineBootyCall.
JSON (JavaScript Object Notation) is a subset of JavaScript that was codified by Douglas. Back in 2005, he wrote json.js, a small library that could parse JSON into JavaScript objects and stringify back in the other direction. It enjoyed significant adoption immediately, but it added the Object.prototype.toJSONString and String.prototype.parseJSON methods which threw many folks for a loop.
In October 2007, Douglas put out json2.js. Its not uncommon for developers to hotlink existing JavaScript versions, and Douglass own copy got its fair share. Soon, his hosting company emailed him asking about the unusually high traffic from a site called OnlineBootyCall.com. Douglas had included in the json2.js code a message that warned: Use your own copy. It is extremely unwise to load code from servers you do not control. He added a browser-locking, synchronous, and JavaScript-freezing modal alert(). The result? A pop-up on every page load of OnlineBootyCall. Ouch.
In this case, Doug was a third-party script developer protecting himself from his users. But more often, its the other way around. For example, json2.js came about partly because Dougs Object.prototype augment wasnt friendly.
This book, written by two of the most expert developers on the subject, takes inventory of all the current techniques and unveils them one by one to help you write battle-hardened script for the first deployment. I hope this book will serve you well, and that youll be as excited about the next generation of the web as I am.
P AUL I RISH
D EVELOPER R ELATIONS :
G OOGLE C HROME , J Q UERY
L EAD D EVELOPER :
M ODERNIZR AND HTML5 B OILERPLATE
Preface
In February of 2010, I was on the phone with Jason Yan, CTO and cofounder of a web startup called Disqus. At the time, Disqus was a tiny company behind a fast-growing commenting application, distributed as a third-party script and popular with bloggers and a handful of large media companies. Jason was interviewing me for a JavaScript engineering roletheir first hire dedicated to working on a fast-growing client codebase.
After a handful of standard JavaScript interview questions involving classes, prototypes, and scopes, Jason took a different tack. He asked me the following (roughly paraphrased) question: Lets say Ive taken a native function prototypelike Array.prototype.indexOf and assigned it a new value. How would you get the original value back?
I was dumbstruck. This was a problem I had never encountered before, and I didnt know the answer. Jason explained to me that the Disqus application executes in environments they dont control. And in those environments, native properties are sometimes overwritten or mangled, properties that they depend on.
I wasnt about to give up on the question. So in the middle of the interview, I opened up my browsers JavaScript console, and started fiddling around with function prototypes. In a few short minutes, I made the startling discovery that you could use JavaScripts delete operator on a modified native property, and the browser would restore the original value.
Jason, as it turns out, was unaware of this solution. He tried out the technique himself and, sure enough, it worked. We were equally excited at this new discovery. We began talking, discussing Disqus current solution to this problem, and the interview changed from a serious interrogation into an excited conversation about iframes, browser hacks, and other scripting gotchas.
I didnt know it at the time, but this was my first taste of Third-party JavaScript; of solving problems that only affect client applications running in other peoples web environments; of discovering techniques and practices that some web developers may never be aware of. And I was hooked.
Several more interviews and two months later, I joined the Disqus team, which only had seven employees at the time, in San Francisco. That was where I met Anton Kovalyov, my new coworker, fellow JavaScripter, and future coauthor. For the next two-plus years, Anton and I were responsible for maintaining and developing Disqus client-side code. Disqus continued to growrapidly. By 2012, it was installed on hundreds of thousands of web pages, and received over 5 billion page views per month. Its customers included CNN, MLB, IGN, Time.com, Rolling Stone, and dozens of other major web and media properties.
During that period of time, Anton and I learned dozens of helpful tricks, tips, and hacks for third-party scripters, most of which we learned the hard way, and some of which we kept under wraps intentionally, because they gave us a technological edge.
In this book, weve pooled our collective knowledge about third-party JavaScript. Not only do we think our book will help third-party scripters everywhere, we also think that the practices we discuss may help make the web a better place for everybody. We hope that by the end of reading it, youll agree.
B EN V INEGAR
Acknowledgments
We found writing this book a daunting and challenging experience, and we recognize that theres no way we could have done it on our own. We want to take a moment and acknowledge the folks who have contributed to this work, both directly and indirectly.