0% found this document useful (0 votes)
12 views

686Professional website performance Optimizing the front end and back end 1st Edition Peter Smith download

The document is a comprehensive guide titled 'Professional Website Performance: Optimizing the Front End and the Back End' by Peter Smith, focusing on enhancing website performance through various techniques for both front-end and back-end development. It includes detailed chapters on web browsers, client-side caching, content compression, and optimization strategies for web servers and databases. The book is published by John Wiley & Sons, Inc., and is available in multiple digital formats for instant download.

Uploaded by

utamyikah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

686Professional website performance Optimizing the front end and back end 1st Edition Peter Smith download

The document is a comprehensive guide titled 'Professional Website Performance: Optimizing the Front End and the Back End' by Peter Smith, focusing on enhancing website performance through various techniques for both front-end and back-end development. It includes detailed chapters on web browsers, client-side caching, content compression, and optimization strategies for web servers and databases. The book is published by John Wiley & Sons, Inc., and is available in multiple digital formats for instant download.

Uploaded by

utamyikah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Professional website performance Optimizing the

front end and back end 1st Edition Peter Smith


pdf download

https://ebookgate.com/product/professional-website-performance-
optimizing-the-front-end-and-back-end-1st-edition-peter-smith/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

High Performance Web Sites Essential Knowledge for Front


End Engineers 1st Edition Steve Souders

https://ebookgate.com/product/high-performance-web-sites-essential-
knowledge-for-front-end-engineers-1st-edition-steve-souders/

ebookgate.com

Front End Drupal Designing Theming Scripting 1st Edition


Konstantin Kafer

https://ebookgate.com/product/front-end-drupal-designing-theming-
scripting-1st-edition-konstantin-kafer/

ebookgate.com

The End of the Performance Review 1st Edition Dr Tim Baker


(Auth.)

https://ebookgate.com/product/the-end-of-the-performance-review-1st-
edition-dr-tim-baker-auth/

ebookgate.com

On Edge Performance at the End of the Twentieth Century C.


Carr

https://ebookgate.com/product/on-edge-performance-at-the-end-of-the-
twentieth-century-c-carr/

ebookgate.com
Modern Front End Development for Rails Hotwire Stimulus
Turbo and React 2nd Edition Noel Rappin

https://ebookgate.com/product/modern-front-end-development-for-rails-
hotwire-stimulus-turbo-and-react-2nd-edition-noel-rappin/

ebookgate.com

Descriptive Metadata for Television An End to End


Introduction 1st Edition Mike Cox

https://ebookgate.com/product/descriptive-metadata-for-television-an-
end-to-end-introduction-1st-edition-mike-cox/

ebookgate.com

Single Page Web Applications JavaScript end to end 1st


Edition Michael S. Mikowski

https://ebookgate.com/product/single-page-web-applications-javascript-
end-to-end-1st-edition-michael-s-mikowski/

ebookgate.com

The end of ethics and a way back how to fix a


fundamentally broken global financial system 1st Edition
Malloch
https://ebookgate.com/product/the-end-of-ethics-and-a-way-back-how-to-
fix-a-fundamentally-broken-global-financial-system-1st-edition-
malloch/
ebookgate.com

Loose End 1st Edition Ivan Coyote

https://ebookgate.com/product/loose-end-1st-edition-ivan-coyote/

ebookgate.com
ffirs.indd ii 05/11/12 5:02 PM
PROFESSIONAL WEBSITE PERFORMANCE

INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii

 PART I FRONT END


CHAPTER 1 A Refresher on Web Browsers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
CHAPTER 2 Utilizing Client-Side Caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
CHAPTER 3 Content Compression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
CHAPTER 4 Keeping the Size Down with Minification . . . . . . . . . . . . . . . . . . . . . . . . . 53
CHAPTER 5 Optimizing Web Graphics and CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .71
CHAPTER 6 JavaScript, the Document Object Model, and Ajax . . . . . . . . . . . . . . . . . 111

 PART II BACK END


CHAPTER 7 Working with Web Servers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
CHAPTER 8 Tuning MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
CHAPTER 9 MySQL in the Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
CHAPTER 10 Utilizing NoSQL Solutions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
CHAPTER 11 Working with Secure Sockets Layer (SSL) . . . . . . . . . . . . . . . . . . . . . . . . 359
CHAPTER 12 Optimizing PHP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375

 PART III APPENDIXES


APPENDIX A TCP Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
APPENDIX B Designing for Mobile Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
APPENDIX C Compression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .417

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427

ffirs.indd i 05/11/12 5:02 PM


ffirs.indd ii 05/11/12 5:02 PM
PROFESSIONAL

Website Performance
OPTIMIZING THE FRONT END AND THE BACK END

Peter Smith

John Wiley & Sons, Inc.

ffirs.indd iii 05/11/12 5:02 PM


Professional Website Performance: Optimizing the Front End and the Back End
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com

Copyright © 2013 by John Wiley & Sons, Inc., Indianapolis, Indiana

Published simultaneously in Canada

ISBN: 978-1-118-48752-5
ISBN: 978-1-118-48751-8 (ebk)
ISBN: 978-1-118-55172-1 (ebk)
ISBN: 978-1-118-55171-4 (ebk)

Manufactured in the United States of America

10 9 8 7 6 5 4 3 2 1

No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108
of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers,
MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the
Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011,
fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.

Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with
respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including
without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or
promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work
is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional
services. If professional assistance is required, the services of a competent professional person should be sought. Neither
the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is
referred to in this work as a citation and/or a potential source of further information does not mean that the author or the
publisher endorses the information the organization or Web site may provide or recommendations it may make. Further,
readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this
work was written and when it is read.

For general information on our other products and services please contact our Customer Care Department within the
United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard
print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD
or DVD that is not included in the version you purchased, you may download this material at http://booksupport
.wiley.com. For more information about Wiley products, visit www.wiley.com.

Library of Congress Control Number: 2012949514

Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trade-
marks or registered trademarks of John Wiley & Sons, Inc. and/or its affi liates, in the United States and other countries,
and may not be used without written permission. All other trademarks are the property of their respective owners. John
Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.

ffirs.indd iv 05/11/12 5:02 PM


To my wife, Stef, and my parents

ffirs.indd v 05/11/12 5:02 PM


ffirs.indd vi 05/11/12 5:02 PM
ABOUT THE AUTHOR

PETER G. SMITH has been a full-time Linux consultant, web developer, and system administrator, with
a particular interest in performance for the past 13 years. Over the years, he has helped a wide range
of clients in areas such as front-end performance, load balancing and scalability, and database opti-
mization. Past open source projects include modules for Apache and OSCommerce, a cross-platform
IRC client, and contributions to The Linux Documentation Project (TLDP).

ABOUT THE TECHNICAL EDITOR

JOHN PELOQUIN is a software engineer with back-end and front-end experience ranging across
web applications of all sizes. Peloquin earned his B.A. in Mathematics from the University of
California at Berkeley, and is currently a lead engineer for a healthcare technology startup, where
he makes heavy use of MySQL, PHP, and JavaScript. He has edited Professional JavaScript for
Web Developers, 3rd Edition by Nicholas Zakas (Indianapolis: Wiley, 2012) and JavaScript
24-Hour Trainer by Jeremy McPeak (Indianapolis: Wiley, 2010). When he is not coding or col-
lecting errata, Peloquin is often found engaged in mathematics,
philosophy, or juggling.

ffirs.indd vii 05/11/12 5:02 PM


ffirs.indd viii 05/11/12 5:02 PM
CREDITS

EXECUTIVE EDITOR PRODUCTION MANAGER


Carol Long Tim Tate

PROJECT EDITOR VICE PRESIDENT AND EXECUTIVE GROUP


Kevin Shafer PUBLISHER
Richard Swadley
TECHNICAL EDITOR
John Peloquin VICE PRESIDENT AND EXECUTIVE PUBLISHER
Neil Edde
PRODUCTION EDITOR
Rosanna Volis ASSOCIATE PUBLISHER
Jim Minatel
COPY EDITOR
San Dee Phillips PROJECT COORDINATOR, COVER
Katie Crocker
EDITORIAL MANAGER
Mary Beth Wakefield PROOFREADER
Nancy Carrasco
FREELANCER EDITORIAL MANAGER
Rosemarie Graham INDEXER
Robert Swanson
ASSOCIATE DIRECTOR OF MARKETING
David Mayhew COVER DESIGNER
Ryan Sneed
MARKETING MANAGER
Ashley Zurcher COVER IMAGE
© Henry Price / iStockphoto
BUSINESS MANAGER
Amy Knies

ffirs.indd ix 05/11/12 5:02 PM


ffirs.indd x 05/11/12 5:02 PM
ACKNOWLEDGMENTS

A LOT OF PEOPLE HAVE BEEN INVOLVED in making this book happen. I’d like to thank everyone at
Wiley for their hard work, especially Carol Long for having faith in my original idea and helping me
to develop it, and Kevin Shafer, my Project Editor, who patiently helped turn my manuscript into
a well-rounded book. Special thanks are also due to John Peloquin, whose technical review proved
invaluable.
I’d also like to take the opportunity to thank my friends and family for being so supportive over the
past few months.

ffirs.indd xi 05/11/12 5:02 PM


ffirs.indd xii 05/11/12 5:02 PM
CONTENTS

INTRODUCTION xxiii

PART I: FRONT END

CHAPTER 1: A REFRESHER ON WEB BROWSERS 3

A Brief History of Web Browsers 3


Netscape Loses Its Dominance 4
The Growth of Firefox 4
The Present 5
Inside HTTP 5
The HyperText Transfer Protocol 5
HTTP Versions 8
Support for Virtual Hosting 9
Caching 9
How Browsers Download and Render Content 10
Rendering 11
Persistent Connections and Keep-Alive 12
Parallel Downloading 14
Summary 21

CHAPTER 2: UTILIZING CLIENT-SIDE CACHING 23

Understanding the Types of Caching 23


Caching by Browsers 23
Intermediate Caches 24
Reverse Proxies 25
Controlling Caching 25
Conditional GETs 25
Utilizing Cache-Control and Expires Headers 28
Choosing Expiration Policies 30
Coping with Stale Content 30
How Not to Cache 31
Dealing with Intermediate Caches 31
Cache-Control Revisited 31
Caching HTTP Responses 32
The Shift in Browser Behavior 32
Using Alternative 3xx Codes 34

ftoc.indd xiii 05/11/12 5:22 PM


CONTENTS

DNS Caching and Prefetching 34


The DNS Resolution Process 35
DNS Caching by the Browser 35
How DNS Lookups Affect Performance 36
DNS Prefetching 36
Controlling Prefetching 37
Summary 37
CHAPTER 3: CONTENT COMPRESSION 39

Who Uses Compression 39


Understanding How Compression Works 41
Compression Methods 42
Other Compression Methods 47
Transfer Encoding 48
Compression in PHP 49
Compressing PHP-Generated Pages 49
Compressing Other Resources 51
Summary 51

CHAPTER 4: KEEPING THE SIZE DOWN WITH MINIFICATION 53

JavaScript Minification 54
YUI Compressor 55
Google Closure 56
Comparison of JavaScript Minifiers 58
CSS Minification 59
Use Shorthand 59
Grouping Selectors 60
CSS Minifiers 60
Improving Compression 62
HTML Minification 63
HTML Minification Techniques 64
HTML Minification Tools 66
Summary 69

CHAPTER 5: OPTIMIZING WEB GRAPHICS AND CSS 71

Understanding Image Formats 71


JPEG 72
GIF 72
PNG 73
SVG 73

xiv

ftoc.indd xiv 05/11/12 5:22 PM


CONTENTS

Optimizing Images 74
Image Editing Software 74
Choosing the Right Format 74
Interlacing and Progressive Rendering 75
PNG Optimization 77
GIF Optimization 80
JPEG Compression 80
Image Optimization Software 84
Data URIs 85
Favicons 85
Using Lazy Loading 87
Avoiding Empty src attributes 88
Using Image Maps 89
CSS Sprites 91
Sprite Strategies 94
Repeating Images 94
CSS Performance 99
CSS in the Document Head 100
Inline versus External 100
Link versus @import 100
Redundant Selectors 100
CSS Expressions 101
Selector Performance 102
Using Shorthand Properties 102
Inheritance and Default Values 104
Doing More with CSS 104
Looking Forward 109
MNG 109
APNG 109
JPEG 2000 110
Summary 110

CHAPTER 6: JAVASCRIPT, THE DOCUMENT OBJECT MODEL,


AND AJAX 111

JavaScript, JScript, and ECMAScript 112


A Brief History of JavaScript 112
JavaScript Engines 112
The Document Object Model 115
Manipulating the DOM 117
Reflowing and Repainting 117
Browser Queuing 119

xv

ftoc.indd xv 05/11/12 5:22 PM


CONTENTS

Event Delegation 119


Unobtrusive JavaScript 120
Memory Management 121
Getting the Most from JavaScript 122
Language Constructs 122
Loading JavaScript 127
Nonblocking of JavaScript Downloads 128
Merging, Splitting, and Inlining 130
Web Workers 134
Ajax 136
XMLHttpRequest 136
Using Ajax for Nonblocking of JavaScript 137
Server Responsiveness 137
Using Preemptive Loading 138
Ajax Frameworks 138
Summary 138

PART II: BACK END

CHAPTER 7: WORKING WITH WEB SERVERS 141

Apache 141
Working with Modules 142
Deciding on Concurrency 145
Improving Logging 146
Miscellaneous Performance Considerations 148
Examining Caching Options 150
Using Content Compression 155
Looking Beyond Apache 158
Nginx 158
Nginx, Apache, and PHP 164
The Best of the Rest 168
Multiserver Setups with Nginx and Apache 169
Nginx as a Reverse Proxy to Apache 170
Proxy Options 171
Nginx and Apache Side by Side 172
Load Balancers 173
Hardware versus Software 173
Load Balancer Features 174
Using Multiple Back-End Servers 176
HAProxy 181
Summary 191

xvi

ftoc.indd xvi 05/11/12 5:22 PM


CONTENTS

CHAPTER 8: TUNING MYSQL 193

Looking Inside MySQL 194


Understanding the Storage Engines 195
MyISAM 195
InnoDB 196
MEMORY 197
ARCHIVE 198
Tuning MySQL 198
Table Cache 198
Thread Caching 202
Per-Session Buffers 204
Tuning MyISAM 205
Key Cache 205
Miscellaneous Tuning Options 210
Tuning InnoDB 211
Monitoring InnoDB 211
Working with Buffers and Caches 212
Working with File Formats and Structures 217
Memory Allocation 218
Threading 219
Disk I/O 219
Mutexes 222
Compression 223
Working with the Query Cache 225
Understanding How the Query Cache Works 225
Configuring the Query Cache 227
Inspecting the Cache 228
The Downsides of Query Caching 232
Optimizing SQL 234
EXPLAIN Explained 234
The Slow Query Log 237
Indexing 239
Query Execution and Optimization 247
Query Cost 248
Tips for SQL Efficiency 249
Summary 254

CHAPTER 9: MYSQL IN THE NETWORK 255

Using Replication 256


The Basics 256

xvii

ftoc.indd xvii 05/11/12 5:22 PM


CONTENTS

Advanced Topologies 264


Replication Performance 270
Miscellaneous Features of Replication 273
Partitioning 273
Creating Partitions 274
Deciding How to Partition 276
Partition Pruning 276
Physical Storage of Partitions 277
Partition Management 278
Pros and Cons of Partitioning 278
Sharding 279
Lookup Tables 280
Fixed Sharding 281
Shard Sizes and Distribution 281
Sharding Keys and Accessibility 281
Cross-Shard Joins 282
Application Modifications 283
Complementing MySQL 283
MySQL Proxy 283
MySQL Tools 286
Alternatives to MySQL 294
MySQL Forks and Branches 294
Full-Text Searching 296
Other RDBMSs 307
Summary 308

CHAPTER 10: UTILIZING NOSQL SOLUTIONS 309

NoSQL Flavors 310


Key-Value Stores 310
Multidimension Stores 310
Document Stores 311
memcache 311
Installing and Running 312
membase — memcache with Persistent Storage 321
MongoDB 325
Getting to Know MongoDB 325
MongoDB Performance 328
Replication 339
Sharding 343
Other NoSQL Technologies 353
Tokyo Cabinet and Tokyo Tyrant 354
CouchDB 354

xviii

ftoc.indd xviii 05/11/12 5:22 PM


CONTENTS

Project Voldemort 355


Amazon Dynamo and Google BigTable 355
Riak 356
Cassandra 356
Redis 356
HBase 356
Summary 356
CHAPTER 11: WORKING WITH SECURE SOCKETS LAYER (SSL) 359

SSL Caching 360


Connections, Sessions, and Handshakes 360
Abbreviated Handshakes 360
SSL Termination and Endpoints 364
SSL Termination with Nginx 365
SSL Termination with Apache 366
SSL Termination with stunnel 367
SSL Termination with stud 368
Sending Intermediate Certificates 368
Determining Key Sizes 369
Selecting Cipher Suites 369
Investing in Hardware Acceleration 371
The Future of SSL 371
OCSP Stapling 371
False Start 372
Summary 372
CHAPTER 12: OPTIMIZING PHP 375

Extensions and Compiling 376


Removing Unneeded Extensions 376
Writing Your Own PHP Extensions 378
Compiling 379
Opcode Caching 381
Variations of Opcode Caches 381
Getting to Know APC 382
Memory Management 382
Optimization 382
Time-To-Live (TTL) 382
Locking 383
Sample apc.ini 384
APC Caching Strategies 384
Monitoring the Cache 386
Using APC as a Generic Cache 386
xix

ftoc.indd xix 05/11/12 5:22 PM


CONTENTS

Warming the Cache 387


Using APC with FastCGI 387
Compiling PHP 388
phc 388
Phalanger 388
HipHop 388
Sessions 389
Storing Sessions 389
Storing Sessions in memcache/membase 390
Using Shared Memory or tmpfs 390
Session AutoStart 391
Sessions and Caching 391
Efficient PHP Programming 392
Minor Optimizations 392
Major Optimizations 392
Garbage Collection 395
Autoloading Classes 396
Persistent MySQL Connections 396
Profiling with xhprof 398
Installing 398
A Simple Example 399
Don’t Use PHP 401
Summary 401

PART III: APPENDIXES

APPENDIX A: TCP PERFORMANCE 405

The Three-Way Handshake 405


TCP Performance 408
Nagle’s Algorithm 408
TCP_NOPUSH and TCP_CORK 408

APPENDIX B: DESIGNING FOR MOBILE PLATFORMS 409

Understanding Mobile Platforms 409


Responsive Content 410
Getting Browser Display Capabilities with JavaScript 411
Server-Side Detection of Capabilities 411
A Combined Approach 412
CSS3 Media Queries 413
Determining Connection Speed 413

xx

ftoc.indd xx 05/11/12 5:22 PM


CONTENTS

JavaScript and CSS Compatibility 414


Caching in Mobile Devices 414
APPENDIX C: COMPRESSION 417

The LZW Family 417


LZ77 417
LZ78 418
LZW 419
LZ Derivatives 420
Huffman Encoding 421
Compression Implementations 424

INDEX 427

xxi

ftoc.indd xxi 05/11/12 5:22 PM


flast.indd xxii 05/11/12 4:57 PM
INTRODUCTION

THE PAST DECADE has seen an increased interest in website performance, with businesses of all
sizes realizing that even modest changes in page loading times can have a significant effect on their
profits. The move toward a faster web has been driven largely by Yahoo! and Google, which have
both carried out extensive research on the subject of website performance, and have worked hard to
make web masters aware of the benefits.
This book provides valuable information that you must know about website performance
optimization — from database replication and web server load balancing, to JavaScript profi ling
and the latest features of Cascading Style Sheets 3 (CSS3). You can discover (perhaps surprising)
ways in which your website is under-performing, and learn how to scale out your system as the
popularity of your site increases.

WHY SPEED IS IMPORTANT


At fi rst glance, it may seem as if website loading speeds aren’t terribly important. Of course, it puts
off users if they must wait 30 seconds for your page to load. But if loading times are relatively low,
isn’t that enough? Does shaving off a couple of seconds from loading times actually make that much
of a difference? Numerous pieces of research have been carried out on this subject, and the results
are quite surprising.
In 2006, Google experimented with reducing the size of its Maps homepage (from 100 KB to
70–80 KB). Within a week, traffic had increased by 10 percent, according to ZDNet (http://www
.zdnet.com/blog/btl/googles-marissa-mayer-speed-wins/3925?p=3925). Google also found
that a half-second increase in loading times for search results had led to a 20 percent drop in sales.
That same year, Amazon.com came to similar conclusions, after experiments showed that for each
100-millisecond increase in loading time, sales dropped by 1 percent (http://ai.stanford
.edu/~ronnyk/IEEEComputer2007OnlineExperiments.pdf).

The fact that there is a correlation between speed and sales perhaps isn’t too surprising, but the
extent to which even a tiny difference in loading times can have such a noticeable impact on sales
certainly is.
But that’s not the only worry. Not only do slow websites lose traffic and sales, work at Stanford
University suggests that slow websites are also considered less credible (http://captology
.stanford.edu/pdf/p61-fogg.pdf). It seems that, as Internet connections have become faster, the
willingness of users to wait has started to wane. If you want your site to be busy and well liked, it
pays to be fast.

flast.indd xxiii 05/11/12 4:57 PM


INTRODUCTION

If all this weren’t enough, there’s now yet another reason to ensure that your site runs quickly. In
2010, Google announced that loading times would play a role in how it ranked sites — that is,
faster sites will rank higher (http://googlewebmastercentral.blogspot.com/2010/04/
using-site-speed-in-web-search-ranking.html). However, loading times carry a relatively
low weight at the moment, and other factors (relevance, backlinks, and so on) are still much more
important.
Hopefully you are now convinced of the need for speed. So, let’s take a look at some of the reasons
why sites are slow.

Why Sites Are Slow


The most common reason why websites run slowly is that they simply weren’t designed with speed
in mind. Typically, the fi rst step in the creation of a site is for a graphics designer to create templates
based on the ideas of the site owner (who is often not technically minded). The graphic designer’s
main goal is an attractive looking interface regardless of size, and the nontechnical site owner gener-
ally wants lots of bells and whistles, again without appreciating the performance impact.
The next step is for a programmer to make things work behind the scenes, which typically involves
a server-side scripting language (such as PHP or Perl) and a back-end database. Sadly, performance
is often low on the programmer’s agenda, too, especially when his or her boss wants to see visible
results fast. It simply isn’t worth the programmer’s time to compress the bloated graphics created by
the designer, or to convert them to sprites.
Another often overlooked fact is that much of the development and testing of a new website will
probably be carried out on a development server under low load. A database query that takes a
couple of seconds to run may not be a problem when the site has only a couple of users. But when
the site goes live, that same query could well slow down the site to a crawl. Tools such as Apache
Benchmark can simulate heavy traffic.
There is also the issue of caching. Those involved in the creation and development of a site typi-
cally already have primed caches. (That is, images and external JavaScript/CSS used by the site will
already be cached in their browsers.) This causes the site to load much faster than it would for fi rst-
time visitors.
Other factors affecting the speed of a website are connection speed and computer “power.”
Developers typically have powerful computers and a good Internet connection, and it’s easy to for-
get that plenty of people (especially in rural locations) still use dial-up modems and computers that
are 10 years old. Care must be taken to ensure that such users are accommodated for.

The Compromise between Functionality and Speed


The creation of a website is often a battle between the designers who want looks and functionality,
and the programmers who want performance. (Sadly, “battle” tends to be a more apt description
than “collaboration.”) Inevitably, some compromises must be made. Both sides tend to be guilty of

xxiv

flast.indd xxiv 05/11/12 4:57 PM


INTRODUCTION

tunnel vision here, but it’s worth trying to develop a rounded view of the situation. Although speed
is important, it’s not the “be all and end all.” In your quest for more and more savings, be wary of
stripping down your website too much.

Scaling Up versus Scaling Out


There are two basic approaches to scaling your website:
➤ Scaling up (sometimes referred to as scaling vertical) means keeping the same number of
servers but upgrading the server hardware. For example, you may run your whole setup from
a single server. As your site gets more traffic, you discover that the server is beginning to
struggle, so you throw in another stick of RAM or upgrade the CPU — which is scaling up.
➤ With scaling out (also referred to as scaling horizontally), you increase the number of
machines in your setup. For example, in the previous scenario, you could place your data-
base on its own server, or use a load balancer to split web traffic across two web servers.

So, which method is best? You’ll hear a lot of criticism of vertical scaling, but in reality, it is a viable
solution for many. The majority of websites do not achieve overnight success. Rather, the user base
steadily increases over the years. For these sites, vertical scaling is perfectly fi ne. Advances in hard-
ware mean that each time you want to upgrade, a machine with more CPU cores, or more memory,
or faster disks will be available.
Scaling up isn’t without its problems, though. You pay a premium for top-of-the-range hardware.
The latest monster server will usually cost more than two mid-range servers with the same overall
power. Also, additional CPU cores and RAM don’t tend to result in a linear increase in perfor-
mance. For example, no matter how much RAM you have, access to it is still along a fi xed-width
bus, which can transfer only at a fi nite rate. Additional CPU cores aren’t a great benefit if your bot-
tleneck is with a single-threaded application. So, scaling up offers diminishing returns, and it also
fails to cope when your site goes stratospheric. For that, you need a topology where you can easily
add additional mid-range servers to cope with demand.
Scaling out is trickier, because it involves more planning. If you have a pool of web servers, you
must think about how sessions are handled, user uploads, and so on. If you split your database over
several machines, you must worry about keeping data in sync. Horizontal scaling is the best long-
term solution, but it requires more thought as to how to make your setup scalable.
Finally, be wary of taking the idea of horizontal scaling to extremes. Some people take the idea
too far, setting up clusters of Pentium I machines because “that’s how Google does it.” Actually,
Google doesn’t do this. Although Google scales out to a high degree, it still uses decent hardware
on each node.
Scaling out isn’t without its drawbacks either. Each additional node means extra hardware
to monitor and replace, and time spent installing and deploying code. The most satisfactory
arrangement tends to be through a combination of scaling up and scaling out.

xxv

flast.indd xxv 05/11/12 4:57 PM


INTRODUCTION

The Dangers of Premature Optimization


There’s a famous quote by Donald Knuth, author of the legendary The Art of Computer
Programming (Reading, MA: Addison-Wesley Professional, 2011). “Premature optimization is the
root of all evil,” he said, and this is often re-quoted in online discussions as a means of dismissing
another user’s attempts at more marginal optimizations. For example, if one developer is contem-
plating writing his or her PHP script as a PHP extension in C, the Knuth quote will invariably be
used to dispute that idea.
So, what exactly is wrong with premature optimization? The fi rst danger is that it adds complex-
ity to your code, and makes it more difficult to maintain and debug. For example, imagine that you
decided to rewrite some of your C code in assembly for optimal performance. It’s easy to fall into
the trap of not seeing the forest for the trees — you become so focused on the performance of one
small aspect of the system that you lose perspective on overall performance. You may be wasting
valuable time on relatively unimportant areas — there may be much bigger and easier gains to be
made elsewhere.
So, it’s generally best to consider optimization only after you already have a good overview of how
the whole infrastructure (hardware, operating system, databases, web servers, and so on) will fit
together. At that point, you will be in a better position to judge where the greatest gains can be made.
That’s not to say you should ignore efficiency when writing your code. The Knuth quote is often mis-
used because it can be difficult to say what constitutes premature optimization, and what is simply
good programming practice. For example, if your application will be reading a lot of information
from the database, you may decide that you will write some basic caching to wrap around these calls,
to cut down on load on the database.
Does this count as premature optimization? It’s certainly premature in the sense that you don’t even
know if these database calls will be a significant bottleneck, and it is adding an extra degree of com-
plexity to your code. But could it not also be classed as simply planning with scalability in mind?
Building in this caching from the outset will be quicker (and probably better integrated) than hacking
it in at a later date.
If you’re tempted to optimize prematurely, stop and consider these two points:
➤ Will there defi nitely be a benefit — and will it be a significant one?
➤ Will it make the code significantly more difficult to maintain or debug?
If the answers are “yes” and “no,” respectively, you should optimize.

Time Is Money
Optimizing is a satisfactory experience — so much so that you may fi nd yourself attempting opti-
mization for the sake of it, rather than because it is needed. That’s not necessarily a bad thing.
Research has shown that even tiny increases in page loading times can have an impact on revenue
and user experience, so optimization doesn’t have to be a case of passively responding to complaints
about speed. But time is also money, and sometimes simply throwing extra hardware at the problem

xxvi

flast.indd xxvi 05/11/12 4:57 PM


INTRODUCTION

is the best solution. Is spending the best part of a week trying to perform further optimizations the
right move, or would spending $100 on a RAM upgrade be just as effective? The latter option seems
like a cop-out but is probably the most cost-effective route.

TOOLS OF THE TRADE


The bottlenecks in an application don’t always occur where you might expect them to, and an
important precursor to optimization is to spend time watching how the application runs.

Waterfall Views
Waterfall views are extremely useful when looking at the front end of a website. These are graphs
showing the order in which the browser is requesting resources, and the time that it takes each
resource to download. Most waterfall tools also show things like the time spent for domain name
service (DNS) lookups, for establishing a TCP connection to the web server, for parsing and render-
ing data, and so on.
There are a lot of waterfall tools out there — some run in your browser; others are websites into
which you enter the URL that you want to check. But many have subtle flaws. For example, one
popular online tool will request any resources contained in commented-out Hypertext Markup
Language (HTML) such as the following:

<!--
<img src="foo.png">
->

Web browsers have the sense to ignore such links, so this tool will give a distorted view of the page
loading process. Another well-known online tool will fetch all the resources (images and fonts)
referenced in the style sheet, even if the selectors containing them are not used in the HTML docu-
ment. Again, in practice, web browsers are smart enough not to make this mistake.

WebPageTest.org
By far, the best online waterfall tool is probably WebPageTest.org (commonly known as WPT),
developed by Google, AOL, and others. It offers dozens of locations around the world from which to
perform tests and has an impressive list of browsers to test in — from Internet Explorer 6 through
to 10, to iPhone, Firefox, and Chrome. Figure I-1 shows WPT in action.
Figure I-1 shows the results page for http://www.google.com. The six images at the top right
indicate how the site scored in what WPT determined to be the six key areas. Remember that this is
just a summary for quick reference and should not be taken as an absolute. For instance, in the test,
google.com scored an “F” for “Cache static content,” yet it is still well optimized. Clicking any of
these scores will give a breakdown of how the grade was determined.

xxvii

flast.indd xxvii 05/11/12 4:57 PM


INTRODUCTION

FIGURE I-1

The way in which a page loads can vary dramatically, depending on whether the user’s cache
is primed (that is, if the user has previously visited the site). Some static resources (such as CSS,
JavaScript, images, and so on) may already be in the browser cache, significantly speeding things up.
So, the default is for WPT to perform a First View test (that is, as the browser would see the target
site if it had an unprimed cache), and a Repeat View test (that is, emulating the effect of visiting
the site with an already primed cache). A preview image is shown for both these tests, and clicking
one brings up the full waterfall graphic, as shown in Figure I-2.

FIGURE I-2

xxviii

flast.indd xxviii 05/11/12 4:57 PM


INTRODUCTION

The horizontal bar shows time elapsed (with resources listed vertically, in the order in which they
were requested). So, the browser fi rst fetched the index page (/), then chrome-48.png, then logo3w
.png, and so on. Figure I-3 shows the fi rst half second in more detail.

FIGURE I-3

The section at the beginning of the fi rst request indicates a DNS lookup — the browser must
resolve www.google.com to an IP address. This took approximately 50 milliseconds. The next
section indicates the time taken to establish a connection to the web server. This includes setting
up the TCP connection (if you’re unfamiliar with the three-way handshake, see Appendix A, “TCP
Performance”), and possibly waiting for the web server to spawn a new worker process to handle the
request. In this example, that took approximately 70 milliseconds.
The next section shows the time to fi rst byte (TTFB). At the beginning of this section, the client has
issued the request and is waiting for the server to respond. There’ll always be a slight pause here
(approximately 120 milliseconds in this example), even for static fi les. However, high delays often
indicate an overloaded server — perhaps high levels of disk contention, or back-end scripts that are
taking a long time to generate the page.
Finally, the server returns a response to the client, which is shown by the fi nal section of the bar.
The size of this section is dependent on the size of the resource being returned and the available
bandwidth. The number following the bar is the total time for the resource, from start to finish.
After the web browser fetches the HTML document, it can begin fetching resources linked to in it.
Note that in request 2, there is no DNS lookup — the browser already has the response cached. For
request 5, the resource resides on a subdomain, ssl.gstatic.com, so this does incur a DNS lookup.
Also notice two vertical lines at approximately the 40-millisecond and 55-millisecond marks. The
fi rst line indicates the point at which the browser began to render the page. The second line indi-
cates the point at which the onLoad event fi red — that is, the point at which the page had fi nished
loading.
You’ll learn more about these waterfall views later in this book — you’ll learn how to optimize the
downloading order, why some of the requests have a connection overhead and others don’t, and
why there are sometimes gaps where nothing seems to be happening.

Firebug
The downside to WPT is that it shows how the page loads on a remote machine, not your own.
Usually, this isn’t a problem, but occasionally you want to test a URL inside a members-only area,

xxix

flast.indd xxix 05/11/12 4:57 PM


INTRODUCTION

or see the page as it would look for someone in your country (or on your ISP). WPT does actually
support some basic scripting, allowing it to log in to htpasswd-protected areas, but this isn’t any
help if you want to log in to something more complicated.
Firebug is a useful Firefox extension that (among other things) can show a waterfall view as a page
loads in your browser. This is perhaps a more accurate portrayal of real-world performance if you’re
running on a modestly powered PC with home broadband because the WPT tests are presumably
conducted from quite powerful and well-connected hardware.
The output of Firebug is similar to that of WPT, complete with the two vertical lines representing
the start and end of rendering. Each resource can be clicked to expand a list of the headers sent and
received with the request.

System Monitoring
This book is intended to be platform-neutral. Whether you run Berkeley Software Distribution
(BSD), Linux, Solaris, Windows, OS X, or some other operating system, the advice given in this
book should still be applicable.
Nevertheless, for system performance-monitoring tools, this will inevitably be quite platform-
specific. Some tools such as netstat are implemented across most operating systems, but the likes
of vmstat and iostat exist only in the UNIX world, and Windows users must use other tools. Let’s
briefly look at the most common choices to see how they work.

vmstat
vmstat is an essential tool on most flavors of UNIX and its derivatives (Linux, OS X, and so on).
It provides information on memory usage, disk activity, and CPU utilization. With no arguments,
vmstat simply displays a single-line summary of system activity. However, a numeric value is usu-
ally specified on the command line, causing vmstat to output data every x seconds. Here’s vmstat
in action with an interval of 5 seconds:

# vmstat 5
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
r b swpd free buff cache si so bi bo in cs us sy id wa
4 0 28528 355120 160112 4283728 0 0 0 0 0 0 20 2 75 4
4 0 28528 353624 160124 4283764 0 0 0 106 817 1303 28 1 71 0
1 0 28528 358008 160128 4283808 0 0 0 1354 926 1511 28 1 71 0
2 0 28528 351380 160132 4283828 0 0 0 167 757 1428 30 1 69 0
2 0 28528 356360 160136 4283940 0 0 0 1309 864 1420 26 1 72 0
3 0 28528 355552 160140 4284012 0 0 10 133 823 1573 37 1 61 0
5 0 28528 349416 160144 4284092 0 0 5 1598 918 1746 30 1 68 0
3 0 28528 353144 160152 4284116 0 0 14 82 791 1301 24 1 74 0
1 0 28528 355076 160156 4284344 0 0 13 1242 839 1803 27 1 71 1

xxx

flast.indd xxx 05/11/12 4:57 PM


INTRODUCTION

The fi rst columns are as follows:


➤ r — This is the number of currently running processes.
➤ b — This is the number of blocking processes.

Blocking processes are those that cannot yet run because they are waiting on the hardware (most
often the disks). Naturally, this is the least-desirable state for a process to be in, and a high number
of blocking processes generally indicates a bottleneck somewhere (again, usually the disks). If the
number of running processes exceeds the number of CPU cores on the system, this can also cause
some degrading of performance, but blocking is the real killer.
The next four columns are similar to the information given by the free command, as shown here:
➤ swpd — This is how much swap memory is in use (expressed in bytes).
➤ free — This is idle memory.
➤ buff — This is memory used for buffers.
➤ cache — This is memory used for caching.

If you’re coming to UNIX from the world of Windows, it’s worth taking some time to ensure that
you are absolutely clear on what these figures mean — in UNIX, things aren’t as clear-cut as “free”
and “used” memory.
The next two columns show swap usage:
➤ si — This is the bytes read in from swap.
➤ so — This is the bytes written out to swap.

Swapping is usually a bad thing, no matter what operating system you use. It indicates insuffi cient
physical memory. If swapping occurs, expect to see high numbers of blocking processes as the CPUs
wait on the disks.
Following are the next two columns:
➤ bi — This is the bytes read from block devices.
➤ bo — This is the bytes written to block devices.

Invariably, block devices means hard disks, so these two columns show how much data is being read
from and written to disk. With disks so often being a bottleneck, it’s worth studying these columns
with the goal of trying to reduce disk activity. Often, you’ll be surprised just how much writing is
going on.

NOTE For a breakdown of which disks and partitions the activity occurs on, see
the iostat command.

xxxi

flast.indd xxxi 05/11/12 4:57 PM


INTRODUCTION

Now, consider the next two columns:


➤ in — This is the number of CPU interrupts.
➤ cs — This is the number of context switches.

At the risk of digressing too much into CPU architecture, a context switch occurs when the CPU
either switches from one process to another, or handles an interrupt. Context switching is an
essential part of multitasking operating systems but also incurs some slight overhead. If your
system performs a huge number of context switches, this can degrade performance.
The fi nal four columns show CPU usage, measured as a percentage of the CPU time:
➤ us — This is the time spent running userland code.
➤ sy — This is the system time (that is, time spent running kernel code).
➤ id — This shows the idle time. (That is, the CPU is doing nothing.)
➤ wa — This shows the time that the CPU is waiting on I/O.

id (idle) is naturally the most preferable state to be in, whereas wa (waiting) is the least. wa indicates
that the CPU has things to do but can’t because it’s waiting on other hardware. Usually, this is the
disks, so check for high values in the io and swap columns.
Whether the CPU will mostly be running user code or kernel code depends on the nature of the appli-
cations running on the machine. Many of the applications discussed in this book spend a lot of time
sending and receiving data over the network, and this is usually implemented at the kernel level.
The previous vmstat example was taken from a web server at a fairly quiet time of the day. Let’s
look at another example, taken from the same server, while the nightly backup process was running:

# vmstat 5
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
r b swpd free buff cache si so bi bo in cs us sy id wa
1 1 26968 330260 161320 4328812 0 0 0 0 0 0 20 2 75 4
4 0 26968 234492 160988 4370996 0 0 5329 6415 1041 3678 25 3 63 8
1 1 26968 238424 158284 4377120 0 0 4729 5066 1035 2128 18 2 71 9
0 2 27020 255812 150904 4386456 0 0 8339 14990 1169 1987 25 2 64 8
1 6 27992 254028 142544 4366768 0 53 10026 13558 1194 3906 44 5 35 15
4 0 27992 261516 138572 4384876 0 0 7706 17494 1081 2029 41 4 39 16
1 1 31648 277228 131832 4374340 0 0 10300 17186 1127 2262 31 3 58 9
1 2 31648 280524 130676 4385072 0 0 3330 5765 915 2059 23 2 68 6
0 1 31648 282496 130220 4385120 0 0 2096 1918 934 1474 21 1 68 10

Although the machine is far from being overloaded, performance is not ideal. You see regular block-
ing processes, disk activity is higher, and the CPUs (this machine had six cores) are spending more
of their time in the waiting (wa) state.

xxxii

flast.indd xxxii 05/11/12 4:57 PM


INTRODUCTION

Depending on your operating system, there may be other data available from vmstat. For example,
the Linux version can give a more detailed breakdown of disk activity (with the –d switch) and can
show statistics on forking (with the –f switch). Check the man pages to see exactly what your system
supports.

perfmon
On Windows, the Performance Monitor (perfmon) shown in Figure I-4 provides similar information.

FIGURE I-4

Don’t underestimate the power of perfmon. The default provides a wealth of information and can be
extended to show all manner of additional data.

WHO THIS BOOK IS FOR


The information in this book is designed to appeal to a wide range of readers, from system
administrators charged with managing busy websites, to web developers looking to write efficient,
high-performance code.
This book makes no assumptions about your underlying operating system, and the information is
(in most cases) equally applicable whether you run OS X, Linux, Windows, FreeBSD, or another
flavor of UNIX. Situations are highlighted in which some of the information depends on the
operating system used.

xxxiii

flast.indd xxxiii 05/11/12 4:57 PM


INTRODUCTION

WHAT THIS BOOK COVERS


A wide range of technologies are in use on the web, and it would be futile to attempt to cover them
all (or at least cover them in sufficient detail). Rather, the discussions in this book concentrate on the
most popular open source technologies — PHP, MySQL, Apache, Nginx, memcache, and mongodb.
In this book, you’ll discover many of the advanced features of these technologies, and the ways
in which they can be utilized to provide scalable, high-performance websites. You’ll learn cur-
rent performance best practices, tips for improving your existing sites, and how to design with
scalability in mind.
The browser market is wide and varied. The discussions in this book focus on the five main web
browsers (which together make up the vast majority of web users) — Internet Explorer, Chrome,
Firefox, Opera, and Safari. Behavior can vary in suitable (but important) ways between versions,
and, in most cases, when particular aspects of browser behavior are examined, the discussion
includes versions from the past 5 years or so. It’s unfortunate (but inevitable) that a sizeable number
of users will not be running the most current version.

HOW THIS BOOK IS STRUCTURED


The book is divided into two parts, covering aspects of website performance related to the front end
(Part I) and the back end (Part II).
In the fi rst part you’ll meet topics such as the HTTP protocol, how web browsers work, browser
caching, content compression, minification, JavaScript, CSS, and web graphics — all essential topics
for web developers. Following are the chapters included in this part of the book:
➤ Chapter 1, “A Refresher on Web Browsers” — This chapter provides a look under the hood
at how the web works. In this chapter, you will meet the HTTP protocol, and features such
as caching, persistent connections, and Keep-Alive.
➤ Chapter 2, “Utilizing Client-Side Caching” — This chapter examines the ways in which
web browsers cache content, and what you can do to control it.
➤ Chapter 3, “Content Compression” — Here you fi nd everything you need to know about
compressing content to speed up page loading times.
➤ Chapter 4, “Keeping the Size Down with Minification” — In this chapter, you discover the
art of minifying HTML, CSS, and JavaScript to further reduce payload sizes.
➤ Chapter 5, “Optimizing Web Graphics and CSS” — Here you learn how to optimize the
most common image formats, and discover ways in which CSS can be used to create lean,
efficient markup.
➤ Chapter 6, “JavaScript, the Document Object Model, and Ajax” — JavaScript is an increas-
ingly important part of the web. In this chapter, you learn about performance aspects of the
language, with an emphasis on interaction with the document object model (DOM).

xxxiv

flast.indd xxxiv 05/11/12 4:57 PM


INTRODUCTION

The second part of the book focuses on the technologies behind the scenes — databases, web
servers, server-side scripting, and so on. Although many of these issues are of more interest to back-
end developers and system administrators, they are vital for front-end developers to understand to
appreciate the underlying system. Following are the chapters included in this part of the book:
➤ Chapter 7, “Working with Web Servers” — This chapter provides everything you need to
know about tuning Apache and Nginx. The second half of the chapter looks at load balanc-
ing and related issues that arise (for example, session affi nity).
➤ Chapter 8, “Tuning MySQL” — In this fi rst of two chapters devoted to MySQL, you meet
the myriad of tuning options and discover the differences between MyISAM and InnoDB.
➤ Chapter 9, “MySQL in the Network” — Here you learn how to scale out MySQL using
such techniques as replication, sharding, and partitioning.
➤ Chapter 10, “Utilizing NoSQL Solutions” — NoSQL is a collective term for lightweight
database alternatives. In this chapter, you learn about two of the most important players:
memcache and mongodb.
➤ Chapter 11, “Working with Secure Sockets Layer (SSL)” — SSL can be a performance
killer, but there are a surprising number of things that you can do to improve the situation.
➤ Chapter 12, “Optimizing PHP” — Perhaps the most popular back-end scripting language,
PHP can have a significant impact on performance. In this chapter, you learn about opcode
caching, and discover how to write lean, efficient PHP.

This book also includes three appendixes that provide additional information:
➤ Appendix A, “TCP Performance” — Transmission control protocol (TCP) and Internet
Protocol (IP) are the protocols that drive in the Internet. In this appendix, you learn about
some of the performance aspects of TCP, including the three-way handshake and Nagle’s
algorithm.
➤ Appendix B, “Designing for Mobile Platforms” — An increasing number of users now
access the web via mobile devices such as cell phones and tablets. These bring about their
own design considerations.
➤ Appendix C, “Compression” — This book makes numerous references to compression.
Here you discover the inner workings of the LZW family, the algorithm behind HTTP com-
pression, and many image formats.

WHAT YOU NEED TO USE THIS BOOK


To get the most out of this book, you should have a basic working knowledge of web development —
HTML, JavaScript, CSS, and perhaps PHP. You should also be familiar with basic system
management — editing files, installing applications, and so on.

xxxv

flast.indd xxxv 05/11/12 4:57 PM


INTRODUCTION

CONVENTIONS
To help you get the most from the text and keep track of what’s happening, we’ve used a number of
conventions throughout the book.

NOTE Notes indicates notes, tips, hints, tricks, and/or asides to the current
discussion.

As for styles in the text:


➤ We highlight new terms and important words when we introduce them.
➤ We show keyboard strokes like this: Ctrl+A.
➤ We show fi lenames, URLs, and code within the text like so: persistence.properties.
➤ We present code in two different ways:

We use a monofont type with no highlighting for most code examples.

We use bold to emphasize code that is particularly important in the present


context or to show changes from a previous code snippet.

ERRATA
We make every effort to ensure that there are no errors in the text or in the code. However, no one
is perfect, and mistakes do occur. If you fi nd an error in one of our books, like a spelling mistake
or faulty piece of code, we would be grateful for your feedback. By sending in errata, you may save
another reader hours of frustration, and, at the same time, you will be helping us provide even
higher-quality information.
To fi nd the errata page for this book, go to http://www.wrox.com and locate the title using the
Search box or one of the title lists. Then, on the book details page, click the Book Errata link. On
this page, you can view all errata that has been submitted for this book and posted by Wrox editors.

NOTE A complete book list, including links to each book’s errata, is also
available at www.wrox.com/misc-pages/booklist.shtml.

If you don’t spot “your” error on the Book Errata page, go to www.wrox.com/contact/techsupport
.shtml and complete the form there to send us the error you have found. We’ll check the information
and, if appropriate, post a message to the book’s errata page and fi x the problem in subsequent
editions of the book.

xxxvi

flast.indd xxxvi 05/11/12 4:57 PM


INTRODUCTION

P2P.WROX.COM
For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a web-based
system for you to post messages relating to Wrox books and related technologies, and to interact
with other readers and technology users. The forums offer a subscription feature to e-mail you
topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors,
other industry experts, and your fellow readers are present on these forums.
At http://p2p.wrox.com, you will fi nd a number of different forums that will help you, not only as
you read this book, but also as you develop your own applications. To join the forums, just follow
these steps:
1. Go to p2p.wrox.com and click the Register link.
2. Read the terms of use and click Agree.
3. Complete the required information to join, as well as any optional information you want to
provide, and click Submit.
4. You will receive an e-mail with information describing how to verify your account and
complete the joining process.

NOTE You can read messages in the forums without joining P2P, but to post
your own messages, you must join.

After you join, you can post new messages and respond to messages other users post. You can read
messages at any time on the web. If you would like to have new messages from a particular forum
e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to
questions about how the forum software works, as well as many common questions specific to P2P
and Wrox books. To read the FAQs, click the FAQ link on any P2P page.

xxxvii

flast.indd xxxvii 05/11/12 4:57 PM


flast.indd xxxviii 05/11/12 4:57 PM
PART I
Front End

 CHAPTER 1: A Refresher on Web Browsers

 CHAPTER 2: Utilizing Client-Side Caching

 CHAPTER 3: Content Compression

 CHAPTER 4: Keeping the Size Down with Minification

 CHAPTER 5: Optimizing Web Graphics and CSS

 CHAPTER 6: JavaScript, the Document Object Model, and Ajax

c01.indd 1 11/26/12 2:44 PM


c01.indd 2 11/26/12 2:44 PM
1
A Refresher on Web Browsers
WHAT’S IN THIS CHAPTER?

➤ Reviewing web browsers and the HTTP protocol


➤ Understanding the steps involved in loading a web page
➤ Getting to know Keep Alive and parallel downloading

To access a website, you need a web browser — the piece of client-side software that requests
resources from a web server and then displays them. Web browsers are one of the most important
pieces of software in the modern Internet, and competition between vendors is fierce — so much
so that many vendors have chosen to give their browsers away for free, knowing that an increased
share of the browser market can indirectly reap profits in other areas.
Although such competition is good news for consumers, it can be a different story for web
developers, who must strive to make their sites display correctly in the myriad of browsers,
each of which has its own idiosyncrasies and nonstandard behavior. To understand how
this situation has evolved, let’s begin by returning to the early days of the World
Wide Web.

A BRIEF HISTORY OF WEB BROWSERS


Although Mosaic is often thought of as the fi rst web browser to hit the market, this isn’t
actually true — that honor falls on WorldWideWeb, a browser developed by Tim Berners-Lee in
1990 at the same time as he developed the HTTP 0.9 protocol. Other browsers soon followed,
including Erwise, ViolaWWW, MidasWWW, and Cello — with Cello being, at this point, the
only browser for Microsoft Windows. The year 1992 also saw the release of Lynx, the first
text-based browser — the others all utilized graphical user interfaces (GUIs).

c01.indd 3 11/26/12 2:44 PM


4 ❘ CHAPTER 1 A REFRESHER ON WEB BROWSERS

In 1993, Marc Andreessen and Eric Bina created Mosaic. Although Mosaic was not as sophisticated
as its competitors, a lot of effort had gone into making it easy to install. And it had one other big
advantage. Previous browsers had mostly been student projects, and as such, they often floundered
after the students graduated. On the other hand, Mosaic had a team of full-time programmers
developing it and offering technical support. Thanks to some clever marketing, Mosaic and the web
were starting to become linked in the minds of the public.
In 1994, a dispute over the naming of Mosaic forced a rebranding, and Netscape Navigator was
born. Unfortunately, regular changes to the licensing terms meant that, for the next few years, there
was ongoing confusion over how free it actually was.
Microsoft entered the market in 1995 with Internet Explorer (IE) 1.0, which was also based on
Mosaic, from whom Microsoft had licensed the code. IE 2.0 followed later that year, with IE 3.0
following in 1996. IE 3.0 was notable for introducing support for cascading style sheets (CSS),
Java, and ActiveX, but Netscape continued to dominate the market, with IE making up only
approximately 10 percent of the market.

Netscape Loses Its Dominance


Over the following years, the market swiftly turned in Microsoft’s favor. By IE 4.0 (released in
1997), Microsoft’s share of the market had increased to 20 percent, and, by the release of IE 5
in 1999, this had risen to 50 percent. Microsoft’s dominance peaked in the fi rst few years of the
twenty-fi rst century, with IE 6.0 (released in 2001) claiming more than 80 percent of the
market.
Microsoft’s aggressive marketing included a decision to bundle IE with Windows. But there’s no
denying that, at this point in the late 1990s, IE was simply the better browser. Netscape was prone
to crashing, it was not as fast as IE, and it was beginning to look distinctly old-fashioned.
In an attempt to revive its fortunes, Netscape decided to release the source code for Navigator,
and branded it as Mozilla (also known as Netscape 5), entrusting it to the newly formed Mozilla
Foundation. Although this was an important turning point in the history of the web, it did little
to help in the immediate future. AOL purchased Netscape, and released Netscape 6 in 2000 and
Netscape 7 in 2002. This failed to halt the downturn, though, and AOL eventually announced the
end of Netscape in 2008, a year after the release of both Netscape 8 and 9 (which, ironically, were
now based on Firefox).

The Growth of Firefox


By 2000, it was clear that Microsoft had won the browser wars, and for the next few years, it
enjoyed unchallenged dominance of the market. However, the Mozilla Foundation was still hard
at work. Mozilla 1.0 was released in 2002 but failed to make much of an impact in the Windows
environment.

c01.indd 4 11/26/12 2:44 PM


Inside HTTP ❘ 5

Some Mozilla developers were becoming increasingly unhappy with the direction Mozilla was tak-
ing, feeling it was becoming increasingly bloated, and branched off their own port of the Mozilla
code. After several changes to the name, this ultimately became Mozilla Firefox — usually referred
to simply as Firefox.
Firefox 1.0 was released in 2004, but it wasn’t until version 2.0, released 2 years later that things
began to take off. Mozilla marketed Firefox heavily to the everyday user as a faster, more secure
alternative to IE; while bloggers and techies were quick to praise the more advanced features.
Finally, it was felt, there was a worthy rival to IE, and by the end of 2006, Firefox’s share of the
market had risen to 10 percent.
Firefox 3.0 was released in 2008, and by the end of 2010, had a market share of approximately
25 to 30 percent. It’s ironic that just as IE’s early growth was boosted by dissatisfaction among
Netscape users, Firefox’s growth was aided enormously by growing dissatisfaction among IE users.
Indeed, it was felt that, having won the browser war, Microsoft had become somewhat complacent,
with IE 6 and 7 being somewhat insipid.

The Present
Microsoft managed to get back on track with the release of IE 8 in 2008. As well as being compliant
with CSS 2.1 and Acid 2, IE 8 fi nally included tabbed browsing — a feature that had been present in
Opera and Firefox for some time.
In 2011, IE 9 was released, boasting CSS 3 support; improved graphics rendering; and a new
JavaScript engine, Chakra, which was capable of better utilizing multicore CPUs. Also in 2011,
Firefox 4 was released with its own new JavaScript engine (JagerMonkey) and hardware graphics
accelerator.

INSIDE HTTP
Before beginning an examination of optimization techniques, it would be beneficial to understand
how the web works. The remainder of this chapter recaps the basics of the HyperText Transfer
Protocol (HTTP), discusses the differences between HTTP 1.0 and 1.1 (in particular, those relating
to performance), and then follows the steps taken when a browser requests a page — from the initial
domain name service (DNS) look-up through to the rendering. Later chapters revisit these steps in
more detail, and you will learn ways to improve performance.

The HyperText Transfer Protocol


HTTP is the means by which web browsers (clients) communicate with web servers and vice versa.
It’s a text-based protocol operating at the application layer, and, as such, HTTP doesn’t concern
itself with issues such as routing or error checking: This is the job of the lower layers such as trans-
mission control protocol (TCP) and Internet Protocol (IP).

c01.indd 5 11/26/12 2:44 PM


Other documents randomly have
different content
FRUIT PUDDING
2½ lbs. any kind fresh fruit—gooseberries, currants, peaches, plums, pears,
apples, raspberries, cherries, apricots, rhubarb, etc.
2 pints (4 cups) milk
1 tablespoonful butter
1 teaspoonful vanilla extract
1 teaspoonful lemon extract
Pinch salt
Sugar
3 eggs
3 heaping tablespoonfuls (3 ozs.) cornstarch

Stew the fruit, with sufficient sugar to sweeten, in a casserole. Mix


the cornstarch to a smooth consistency with a little of the milk. Bring
the rest of the milk to the boil, stir into it the mixed cornstarch, add
the butter, salt, extracts, and two heaping tablespoonfuls of sugar.
Boil for a quarter of an hour, stirring all the time, remove from the
fire, and add the eggs well beaten.
Pour the hot mixture over the stewed fruit, then brown in a
moderate oven. This makes a delicious covering.
GINGER PUDDING
4 ozs. (4 heaping tablespoonfuls) preserved ginger
4 heaping tablespoonfuls chopped suet
4 ozs. (4 heaping tablespoonfuls) sugar
2 tablespoonfuls ginger syrup
Pinch salt
¼ teaspoonful grated nutmeg
3 eggs
1 heaping teaspoonful baking powder
¾ pint (1½ cups) milk
4 ozs. (4 heaping tablespoonfuls) flour
4 ozs. (1 cup) bread crumbs or cake crumbs
Ginger sauce

Chop the ginger and the suet and put them into a basin; then add
the eggs well beaten and all the other ingredients. Mix together
thoroughly, pour into a well-buttered casserole, cover with the lid or
a buttered paper, and steam for two and a half hours.
Serve with ginger sauce.
The sauce may be made as follows: Beat up the whites of two eggs
to a stiff froth, add half a cupful of whipped cream, one tablespoonful
of finely chopped ginger, and enough of the syrup to give it a strong
flavor.
GREEN-GAGE PUFFS
Some stewed green-gages
½ lb. (2 cups) flour
1 egg
2 teaspoonfuls baking powder
½ teaspoonful salt
Some milk
½ teaspoonful lemon extract

Sift the flour into a basin with the baking powder and the salt, beat
up the egg, and add a little milk to it, then add them gradually with
the lemon extract to the dry ingredients, making a stiff batter. Put
half a tablespoonful of this batter into buttered earthenware cups,
then put in some stewed green-gages; put a tablespoonful of the
batter on the top and cover with a buttered paper. Steam steadily for
twenty minutes.
These puffs may be baked in the oven. Any kind of stewed or fresh
fruit may be used.
MONTE CARLO CHERRIES
½ lb. large ripe cherries
¼ lb. lump sugar
1 gill (¼ pint) water
1 dessertspoonful arrowroot
Some Kirsch

Stone the cherries, put them into a saucepan with the sugar and
the water. Let them boil gently for ten minutes. Blend the arrowroot
with two tablespoonfuls of cold water and stir it among the cherries.
Divide the cherries into small casseroles, pour a liqueur-glassful of
Kirsch on the top of each, and set alight.
Send to the table burning.
ORANGE MERINGUE PUDDING
3 oranges
4 eggs
½ pint (1 cup) milk
2 heaping tablespoonfuls (2 ozs.) butter
½ pint (1 cup) bread crumbs
3 heaping tablespoonfuls (3 ozs.) sugar

Bring the milk and the butter to boiling point, then pour them over
the bread crumbs; mix in the sugar and the yolks of the eggs; set
aside till cold, then mix in the grated rind and the pulp of the
oranges, mix all thoroughly together, and pour into a buttered
earthenware pudding dish; bake in a moderate oven until set.
Beat up the whites of the eggs till stiff, then gradually beat into
them three tablespoonfuls of sugar. Decorate the top of the pudding
with this meringue, and return to the oven to brown.
PARISIAN PEARS
6 juicy pears
½ cupful macaroon crumbs
2 tablespoonfuls cream
1 tablespoonful sherry wine
1 teaspoonful vanilla extract
6 rings of angelica
6 candied violets
2 cupfuls steamed rice

Peel the pears and stew them in a little sugar syrup flavored with
vanilla. Take them out when tender, cut them in halves, and remove
the centers.
Mix the macaroon crumbs with the cream and the sherry wine,
and divide them into the pear cavities. Cook the rice in milk till
tender and flavor it with a little vanilla extract. Line some flange
ramequins with it. Put the pear halves together and mount them,
pyramid shape, on the rice.
Crown each pear with a ring of angelica, and in the center of each
ring put a candied violet.
PEACH SOUFFLÉ
6 ripe peaches
4 heaping tablespoonfuls (4 ozs.) sugar
½ pint (1 cup) water
2 heaping tablespoonfuls (2 ozs.) flour
1 heaping tablespoonful (1 oz.) butter
¼ pint (½ cup) milk
3 eggs
1 egg white

Peel the peaches, put them into a casserole with the sugar and the
water; cook till tender; then rub through a sieve.
Blend the butter and flour in a saucepan over the fire, add the milk
gradually, and stir over the fire till it boils; then add the peach purée
and boil again for three minutes.
Remove the saucepan from the fire; add the yolks of eggs one by
one; then the whites of eggs beaten up stiffly.
Put into a buttered earthenware dish and bake for half an hour.
It may be steamed for three-quarters of an hour.
PEAR DAINTY
1 can preserved pears
5 ozs. (5 heaping tablespoonfuls) sugar
2 pints (4 cups) milk
3 ozs. (3 heaping tablespoonfuls) cornstarch
4 eggs
1 teaspoonful rose extract

Mix the cornstarch to a smooth cream with a little of the milk.


Bring the rest of the milk to the boil in a fireproof dish, remove from
the fire, and stir in the mixed cornstarch.
Beat up the yolks of the eggs with three tablespoonfuls of the
sugar, and stir well into the cornstarch. Cook the whole for a quarter
of an hour, stirring all the time.
Then pour the whole into a buttered casserole, and bake in a
moderate oven till firm. Pour over it the pears and add the rose
extract.
Beat up the whites of the eggs to a stiff froth, add the remaining
sugar to them.
Spread this meringue over the top of the pears, and return to the
oven to brown.
PLUM PUDDING
¼ lb. (1 cup) bread crumbs
4 ozs. (1 cup) flour
4 ozs. (1 cup) brown sugar
1 cupful chopped suet
1 lemon
1 teaspoonful baking powder
½ teaspoonful salt
4 eggs
Milk to moisten
1 cupful chopped citron peel
½ cupful blanched, chopped almonds
½ pint (1 cup) Sultana raisins
½ pint (1 cup) currants
½ pint (1 cup) seeded raisins
1 teaspoonful powdered allspice
½ teaspoonful grated nutmeg
1 teaspoonful powdered ginger
1 teaspoonful powdered cinnamon
1 wineglassful brandy

Beat up the eggs, add the strained juice of the lemon and all the
other ingredients, turn into a well-buttered casserole, cover, and
steam steadily for five hours.
Serve with hard sauce.
PRUNE AND APPLE TART
½ lb. stoned prunes
1 lemon
3 lbs. apples
½ lb. (1 cup) sugar
Pastry
1 egg

Wash and stone the prunes; peel, core, and slice the apples. Put
them into a casserole, sprinkle in the sugar and the grated rind of the
lemon.
Cover neatly with pastry, brush over the top with beaten egg, and
bake in a hot oven for about three-quarters of an hour.
Sprinkle over with sugar and serve hot or cold.
PRUNE PUDDING
½ lb. prunes
½ lemon
1 tablespoonful cornstarch
½ pint (1 cup) milk
2 eggs
2 heaping tablespoonfuls (2 ozs.) sugar
2 heaping tablespoonfuls (2 ozs.) currants
1 inch cinnamon stick
1 wineglassful port wine

Wash the prunes and stew them gently with sufficient water to
cover, adding also the sugar, cinnamon, lemon rind, and strained
juice. When tender, remove the cinnamon and lemon rind; stone the
prunes and rub them through a sieve. Crack half of the stones and
chop the kernels, add them to the prune pulp, and allow to cool a
little.
Clean the currants and soak them in the wine. Mix them with the
cornstarch and add them to the prune mixture, with the yolks of eggs
and the whites stiffly beaten. Pour into a buttered earthenware dish,
dredge with sugar, and bake for half an hour in a fairly hot oven.
Serve hot.
PUMPKIN PIE
½ pint (1 cup) stewed pumpkin
4 heaping tablespoonfuls (4 ozs.) sugar
½ teaspoonful powdered ginger
½ teaspoonful powdered cinnamon
¼ teaspoonful grated nutmeg
1 teaspoonful lemon extract
2 eggs
1 tablespoonful cornstarch
½ pint (1 cup) cream
2 tablespoonfuls melted butter

Line an earthenware pie-plate with pastry. Moisten the cornstarch


with three tablespoonfuls of the cream. Bring the rest of the cream to
boiling point, stir in the cornstarch, and continue stirring until
thickened. Remove from the fire, add the eggs well beaten and all the
other ingredients. Turn into the prepared pie-plate and bake in a
moderate oven for about one hour.
RHUBARB MERINGUE
1 lb. pink rhubarb
4 ozs. (4 heaping tablespoonfuls) sugar
4 eggs
1 lemon
2 tablespoonfuls sugar

Wash the rhubarb and cut it into inch lengths; stew it with the
sugar till tender; strain the juice into a basin, and rub the fruit
through a sieve.
Reduce the juice to half a cupful, mix it with the fruit purée, add
the yolks of the eggs well beaten and the grated rind of the lemon.
Turn into a buttered fireproof dish and bake for half an hour.
Beat up the whites of the eggs to a stiff froth, then beat into them
two tablespoonfuls of sugar; spread over the pudding, dust over with
sugar, and return to the oven for ten minutes to set the meringue.
RICE PUDDING
½ lb. (1 heaping cup) rice
2 quarts (8 cups) milk
½ lb. (1 cup) sugar
1 teaspoonful salt
2 heaping tablespoonfuls (2 ozs.) butter
¼ teaspoonful grated nutmeg
1 teaspoonful rose extract

Wash the rice and soak it in one quart of the milk for one hour.
Add the rest of the milk, the sugar, salt, butter, nutmeg, and rose
extract. Turn into a buttered earthenware dish and bake slowly for
two hours.
STEWED APRICOTS WITH CUSTARD
12 apricots
4 tablespoonfuls sugar
4 eggs
1 pint (2 cups) cream
1 gill (¼ pint) rum
A few slices sponge cake
½ pint (1 cup) hot water

Peel the apricots and cut them into halves, removing the stones.
Put them into a casserole with two tablespoonfuls of the sugar and
the water. Simmer till tender.
Put the sponge cake into an earthenware dish, lay the apricots on
them. Beat up the eggs with the rest of the sugar, add the cream to
them, then pour them into a double boiler. Stir over the fire till quite
smooth, then add the rum.
Pour this over the apricots and serve hot.
STRAWBERRY BATTER PUDDING
1 pint strawberries
1 pint (2 cups) milk
2 tablespoonfuls melted butter
1½ pints (3 cups) flour
3 eggs
1 teaspoonful baking powder
½ teaspoonful salt
1 teaspoonful strawberry extract
Hard sauce

Add the milk gradually to the flour, add the eggs well beaten, salt,
baking powder, and butter. Dredge the strawberries with flour, stir
them into the batter, add the strawberry extract, and turn into a
buttered earthenware dish. Cover and steam for three hours.
Serve with hard sauce.
STRAWBERRY CUSTARDS
5 eggs
½ lb. (1 cup) ripe strawberries or strawberry jam
½ lemon
1 teaspoonful strawberry extract
4 ozs. (4 heaping tablespoonfuls) sugar
Few drops red coloring

Remove the green stalks from the strawberries, place the berries in
a basin, beat until quite liquid, then add the yolks of the eggs well
beaten, sugar, strained lemon juice, and strawberry extract.
Pour the mixture into a fireproof dish, stand it in a saucepan of
boiling water, and stir it over the fire till it thickens: it must not boil.
Allow to get cold then add the stiffly beaten whites of the eggs, stir
lightly till all is well mixed.
Pour into earthenware custard cups, and serve cold decorated with
a ripe strawberry on the top of each custard.
VANILLA CUSTARD
1 pint (2 cups) milk
4 eggs
4 heaping tablespoonfuls (4 ozs.) sugar
1 teaspoonful vanilla extract

Beat the eggs and the sugar together, then add the milk and the
vanilla extract. Divide the mixture into buttered earthenware custard
cups, cover with buttered papers, and steam gently for half an hour.
VERMICELLI PUDDING
¼ lb. vermicelli
1 pint (2 cups) boiling milk
1 oz. (1 heaping tablespoonful) butter
2 ozs. (2 heaping tablespoonfuls) sugar
2 tablespoonfuls finely chopped blanched almonds
3 eggs
Grated rind 1 lemon
¼ teaspoonful grated nutmeg

Crush the vermicelli in the hand till it is in quite short pieces. Put it
into the boiling milk, then add the butter, and stir over the fire till it
becomes thick; this will take a quarter of an hour. Remove from the
fire, add the sugar, almonds, grated rind of lemon, nutmeg, and the
yolks of the eggs, stir all to mix thoroughly, then add the stiffly
beaten whites and stir them in gently. Pour into a well-buttered
earthenware dish, cover with the lid or a buttered paper, and steam
for one hour. Serve with sweet sauce.
The pudding can be baked in a moderate oven till it is nicely
browned. Serve with cream.
WALNUT PUDDING
16 walnuts
1 oz. (1 heaping tablespoonful) butter
1 teaspoonful almond extract
½ teaspoonful vanilla extract
Pinch salt
2 heaping tablespoonfuls browned bread crumbs
1 pint (2 cups) milk
3 eggs

Blanch the walnuts, then chop them finely, and mix with the bread
crumbs; put them into a fireproof dish with the milk, and allow to
boil up; then simmer for ten minutes.
Remove from the fire, and when cool stir in the yolks of the eggs
one by one, add the salt, extracts, and the sugar; mix thoroughly.
Beat up the whites to a stiff froth, and fold them in gently.
Bake for half an hour in a moderate oven.
INVALID RECIPES

“Eat in measure and defy the doctor”

APPLE PURÉE
1 lb. apples
1 teaspoonful butter
2 heaping tablespoonfuls (2 ozs.) sugar
1 teaspoonful grated lemon rind
1 bay leaf
1 tablespoonful orange flower water
2 egg whites

Peel, core, and slice the apples; put them into a casserole, with the
butter, sugar, lemon rind, bay leaf, and orange flower water.
Put the cover on the casserole and cook slowly to a pulp; rub
through a sieve, and with it about three parts fill some small
casseroles.
Beat up the eggs, then add two tablespoonfuls of sugar to them.
Decorate the purée with this meringue and serve hot.
BAKED MILK
1 quart (4 cups) milk
Fresh or stewed fruit

Baked milk is often recommended as a dish for invalids. Put the


milk into an earthenware jar, cover it closely, and allow it to bake
very slowly for several hours in a moderately hot oven.
It should be thick and of a creamy consistency.
Serve with fresh or stewed fruit.
BARLEY GRUEL
2 heaping tablespoonfuls (2 ozs.) pearl barley
1 strip lemon rind
1 quart (4 cups) water
1 heaping tablespoonful (1 oz.) sugar
1 wineglassful sherry wine

Wash the barley thoroughly; put it into a casserole with the water
and the lemon rind and simmer until reduced to half the quantity;
strain and add the sugar, reheat in the casserole, and add the wine.
BEEF TEA EN CASSEROLE
1 lb. lean beef
1 pint (2 cups) water
Salt

Cut the beef into pieces, then shred it with a sharp knife, keeping
back the fat and sinews; put the shredded meat into a casserole with
a pinch of salt and the cold water; cover and allow it to stand in a
cool place for two hours; then set it in the oven for two hours.
Remove the fat and serve hot.
CALF’S SWEETBREADS
2 calf’s sweetbreads
½ pint (1 cup) milk
½ pint (1 cup) white sauce
1 teaspoonful chopped parsley
Salt and pepper

Wash the sweetbreads and soak them in cold water for one hour.
Drain them and put them into a saucepan, cover with cold water, and
bring to the boil. Lift them into another saucepan, cover with the
milk, let them simmer for twenty minutes. Trim them and remove all
the fat and gristle.
Warm the sauce in a casserole, season it nicely, put in the
sweetbreads cut in slices, and cook slowly until they are tender.
Sprinkle the chopped parsley on the top and serve hot.
CHICKEN PANADE
1 chicken breast
2 tablespoonfuls cream
Salt and pepper

Cut the chicken into small pieces and shred it finely; put this into
an earthenware dish or jar with as much water as will cover it, add a
pinch of salt, and cover with paper; stand the jar in a pan of boiling
water, allowing the water to come within an inch of the top; cook in
this way for two hours; strain the liquid from the chicken, pound it
thoroughly and rub it through a sieve, using the liquid to help it
through; reheat, add the cream, and add a little more seasoning if
required.
COLD LEMON PUDDING
1 lemon
½ pint (1 cup) water
1 tablespoonful arrowroot
1 tablespoonful sugar
2 egg whites

Grate the lemon into a fireproof dish, add the water, and bring to
boiling point. Mix the arrowroot with the sugar and strained lemon
juice, then pour into the boiling water and stir over the fire till thick.
Beat up the whites of eggs and stir them in lightly.
Serve cold in a dainty casserole.
FRIAR’S OMELET
5 apples
4 tablespoonfuls sugar
½ teaspoonful powdered cinnamon
1 tablespoonful butter
5 eggs
2 tablespoonfuls brown bread crust

Peel, core, and slice the apples into a saucepan, add the sugar,
butter, and cinnamon. Cook till tender and rub through a sieve. Add
the bread crumbs, yolks of the eggs, and the whites of the eggs stiffly
beaten.
Turn into a buttered fireproof dish, dredge the top with sugar,
bake in a moderate oven for twenty minutes.
Serve hot.
INVALID PUDDING
½ pint (1 cup) milk
1 heaping tablespoonful (1 oz.) butter
1 tablespoonful sugar
1 heaping tablespoonful (1 oz.) rice flour
2 egg whites
2 tablespoonfuls cream
Little grated nutmeg

Put the milk, butter, sugar, and grated nutmeg into a saucepan and
bring to boiling point. Mix the rice flour with the cream and stir into
the boiling milk.
Allow to cool for a minute, then add the whites of eggs stiffly
beaten.
Pour into a buttered fireproof dish and bake quickly.
JELLIED FISH
1 flounder
½ pint (1 cup) water
Salt and pepper
1 heaping tablespoonful powdered gelatine
1 teaspoonful lemon juice
1 teaspoonful chopped parsley

Skin and fillet the flounder. Season the fillets with salt and pepper,
roll them up tightly, lay in a small fireproof dish, sprinkle the
chopped parsley over them, add the lemon juice and the gelatine
mixed with the water.
Bake for half an hour in a moderate oven.
Serve cold garnished with parsley.
MILK SOUP
1 pint (2 cups) milk
1 celery stalk
1 egg
Salt, pepper, and grated nutmeg to taste
½ cupful soft bread crumbs

Chop the celery and put it into an earthenware pan, add the bread
crumbs and the milk; allow it to simmer for a quarter of an hour,
then strain it.
Beat up the egg and add it to the soup; reheat it but do not allow it
to boil again.
Season nicely with salt, pepper, and nutmeg.
MULLED MILK
1 pint (2 cups) milk
1 oz. (1 heaping tablespoonful) sugar
2 egg yolks
1 inch cinnamon stick

Put the milk and cinnamon stick into a fireproof pan, bring to
boiling point, and boil for four minutes.
Mix the yolks of the eggs, sugar, and three tablespoonfuls of cold
milk together; strain the hot milk and add it to the eggs, then stir it
over the fire until it begins to thicken—it must not boil; pour it
several times from one earthenware pitcher to another.
OYSTER SOUP
12 oysters
2 tablespoonfuls butter
2 tablespoonfuls flour
½ pint (1 cup) oyster liquor
½ pint (1 cup) cream
Salt, pepper, and grated nutmeg to taste
4 tablespoonfuls milk
Toast points

Strain the liquor from the oysters, rinse them, and cut them into
four pieces. Melt the butter, stir in the flour, add the milk, oyster
liquor, seasonings, and cream, bring to boiling point and pour over
the oysters in petites marmites.
Serve with toast points.
RASPBERRY SOUFFLÉ
½ pint (1 cup) raspberries
2 heaping tablespoonfuls (2 ozs.) sugar
4 tablespoonfuls water
1 heaping tablespoonful (1 oz.) butter
1 heaping tablespoonful (1 oz.) flour
3 tablespoonfuls cream
2 eggs

Put the raspberries into a saucepan with the sugar and the water;
stir over the fire with a wooden spoon till the fruit is tender, then rub
through a sieve; return to the pan, add the butter, flour, and cream;
stir until it boils, remove from the fire, add the yolks of eggs and the
whites stiffly beaten.
Turn into a buttered earthenware dish and bake in a moderate
oven for twenty minutes.
Serve at once.
SAGO GRUEL
2 tablespoonfuls sago
1 tablespoonful sugar
1 pint (2 cups) water
¼ teaspoonful salt
1 wineglassful sherry wine
Juice ½ lemon
Grated nutmeg and ginger to taste

Put the sago and water into a casserole, add the salt, and let it
stand for two hours to soften; then boil it, stirring constantly, until it
is thick, add the wine, sugar, strained lemon juice, ginger, and
nutmeg.
This is an excellent gruel for invalids.
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like