686Professional website performance Optimizing the front end and back end 1st Edition Peter Smith download
686Professional website performance Optimizing the front end and back end 1st Edition Peter Smith download
https://ebookgate.com/product/professional-website-performance-
optimizing-the-front-end-and-back-end-1st-edition-peter-smith/
https://ebookgate.com/product/high-performance-web-sites-essential-
knowledge-for-front-end-engineers-1st-edition-steve-souders/
ebookgate.com
https://ebookgate.com/product/front-end-drupal-designing-theming-
scripting-1st-edition-konstantin-kafer/
ebookgate.com
https://ebookgate.com/product/the-end-of-the-performance-review-1st-
edition-dr-tim-baker-auth/
ebookgate.com
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
https://ebookgate.com/product/descriptive-metadata-for-television-an-
end-to-end-introduction-1st-edition-mike-cox/
ebookgate.com
https://ebookgate.com/product/single-page-web-applications-javascript-
end-to-end-1st-edition-michael-s-mikowski/
ebookgate.com
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
INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
Website Performance
OPTIMIZING THE FRONT END AND THE BACK END
Peter Smith
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)
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.
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.
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).
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.
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.
INTRODUCTION xxiii
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
xiv
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
xv
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
xvii
xviii
xx
INDEX 427
xxi
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.
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.
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.
xxiv
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.
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
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
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.
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
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
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
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
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
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
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.
xxxiii
xxxiv
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.
xxxv
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.
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
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
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.
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.
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.
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
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
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
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
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