<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Witslog Wiki &#187; Speed up a website</title>
	<atom:link href="http://witslog.com/wiki/category/technical/speed-up-a-website/feed" rel="self" type="application/rss+xml" />
	<link>http://witslog.com/wiki</link>
	<description>Technical Log</description>
	<lastBuildDate>Fri, 14 May 2010 06:17:11 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Empty image src can destroy your site</title>
		<link>http://witslog.com/wiki/technical/speed-up-a-website/empty-image-src-can-destroy-your-site</link>
		<comments>http://witslog.com/wiki/technical/speed-up-a-website/empty-image-src-can-destroy-your-site#comments</comments>
		<pubDate>Sun, 28 Mar 2010 11:18:52 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Speed up a website]]></category>

		<guid isPermaLink="false">http://witslog.com/wiki/?p=131</guid>
		<description><![CDATA[This is a problem I’ve come across frequently, and since it has come up again recently, I thought I’d explore this issue in the hope that it will save others some trouble. There are so many problems that this one issue can lead to that...]]></description>
			<content:encoded><![CDATA[<p>This is a problem I’ve come across frequently, and since it has come up again recently, I thought I’d explore this issue in the hope that it will save others some trouble. There are so many problems that this one issue can lead to that it’s baffling browsers still behave this way. The issue? An HTML image, either via <code>&lt;img&gt;</code> tag or JavaScript <code>Image</code> object, that has its <code>src</code> set to “” (an empty string).</p>
<h2>The offending code</h2>
<p>There are basically two patterns to identify. The first pattern is just straight HTML:</p>
<pre><code>&lt;img src="" &gt;</code></pre>
<p>The second pattern is JavaScript and involves the dynamic setting of the <code>src</code> property on either a newly created image or an existing one:</p>
<pre><code>var img = new Image();
img.src = "";</code></pre>
<p>Both patterns cause the same effect: another request is made to your server. There are two different ways that browsers do this.</p>
<ul>
<li>Internet Explorer makes a request to the directory in which the page is located. For example, if you have a page running at <code>http://www.example.com/dir/mypage.htm</code> that has one of these patterns, IE makes a request to <code>http://www.example.com/dir/</code> to fill in the image.</li>
<li>Safari and Chrome make a request to the actual page itself. So the page running at <code>http://www.example.com/dir/mypage.htm</code> results in a second request to <code>http://www.example.com/dir/mypage.htm</code> to fill in the image.</li>
</ul>
<p>You’ll note that Opera and Firefox aren’t mentioned at all. Opera behaves as you might expect: it doesn’t do anything when an empty image <code>src</code> is encountered; the attribute is ignored. Firefox 3 and earlier behave the same as Safari and Chrome, but Firefox 3.5 addressed this issue and no longer sends a request (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=444931">related bug</a>).</p>
<p>Both cases, of course, are problematic because it’s an image making a request for a document. You can easily see this behavior using an HTTP debugging proxy (I highly recommend <a href="http://www.fiddlertool.com/">Fiddler</a>).</p>
<h2>The problems</h2>
<p>There are two basic problems that this browser behavior causes. The first is a traffic spike.&nbsp; Imagine that have <code>&lt;img src=""&gt;</code> on the page at <code>http://www.example.com/</code>. The big problem is that each instance of <code>&lt;img src=""&gt;</code> makes a request to <code>/</code> in all browsers, which is the homepage of the domain. Congratulations, you’ve effectively doubled your traffic to the homepage.</p>
<p>For small sites, this may not be that big of a deal; jumping from 10,000 to 20,000 page views probably isn’t going to raise any flags for you or your host. If you’re a page that gets millions of page views per day, and probably have a lot of machines to handle that load, doubling or tripling traffic can be crippling. You can very easily run out of capacity.</p>
<p>Another issue with the traffic increase is the computing power needed to generate that homepage. If the page is personalizable or is updated with some regular frequency, you could be wasting computing cycles creating a page that will never be viewed by anyone.</p>
<p>The second problem is user state corruption. If you’re tracking state in the request, either by cookies or in another way, you have the possibility of destroying data. Even though the image request doesn’t return an image, all of the headers are read and accepted by the browser, including all cookies. While the rest of the response is thrown away, the damage may already be done.</p>
<h2>How does this code happen?</h2>
<p>The first time I encountered this problem, I naively thought that it was a bad developer writing crappy code. Had this been 2000 or earlier, I probably would have been right. In today’s web development world, however, I’m mostly wrong. Today, there are so many templating engines and content management systems responsible for constructing pages on-the-fly that it’s quite possible for good developers to end up producing pages with this code. All it takes is something as simple as this PHP:</p>
<pre><code>&lt;img src="$imageUrl" &gt;</code></pre>
<p>If some other part of the code is responsible for filling in <code>$imageUrl</code>, and that code fails, then the offending code gets output to the browser.</p>
<p>In today’s web development world, we’re all doing something along these lines, whether we know it or not. Download a new Wordpress theme? Make sure you’ll filled in all default arguments. Using a CMS at work? Make sure all your image URL fields are validated. It’s frightening easy to end up with this bad code on your page.</p>
<h2>Other tags with problems</h2>
<p>Before getting too angry at browser vendors, I think it’s fair to take a look at the <a href="http://www.w3.org/TR/html4/">HTML 4 specification</a>, specifically the part <a href="http://www.w3.org/TR/html4/struct/objects.html#h-13.2">defining images</a>. Even though the specification indicates that the <code>src</code> attribute should contain a URI, it fails to define the behavior when <code>src</code> doesn’t contain a URI. Of course, images aren’t the only tags that reference an external resource, and so it should come as no surprise that there are other tags with the same problem.</p>
<p>As it turns out, Internet Explorer is the most sane browser out there. It’s problems are thankfully limited to images with an empty <code>src</code> attribute. It does make for this by making it a pain to detect, but that will be discussed later.</p>
<p>For other browsers, there are two additional problem scenarios: <code>&lt;script src=""&gt;</code> and <code>&lt;link href=""&gt;</code>. Chrome, Safari, and Firefox all initiate another request.</p>
<p>Thankfully, no browser has a problem with <code>&lt;iframe src=""&gt;</code>, as all correctly do not make another request.</p>
<h2>What can be done?</h2>
<p>Of course, the best thing to do is eliminate the offending code from your pages whenever possible. That’s fixing the problem at the source. If you can’t do that, though, your next best option is to attempt to detect it on the server and abort any further execution.</p>
<p>For browsers other than IE, it’s not too difficult to detect what’s going on from the server side. Since the request comes back to the exact same location that contains the offending code, there are two things you can do. First, you can check the request’s referrer. A request resulting from this issue coming from <code>http://www.example.com/dir/mypage.htm</code> will have a referrer of <code>http://www.example.com/dir/mypage.htm</code>. Assuming that there are <em>no valid situations under which your page links to itself</em>, this is a fairly safe way to detect these requests on the server-side.</p>
<p>Internet Explorer throws a wrench into the works by sending the request to the directory of the page instead of the page itself. If you’re only using path URLs (i.e., nothing with a file extension), then the effect is the same and you can use the same referrer detect. Some sample code for use with PHP:</p>
<pre><code>&lt;?php
    //Works for IE only when using path URLs and not file URLs

    //get the referrer
    $referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

    //current URL (assuming HTTP and default port)
    $url = "http://" . $_SERVER['HTTP_HOST']&nbsp; . $_SERVER['REQUEST_URI'];

    //make sure they're not the same
    if ($referrer == $url){
        exit;
    }
?&gt;</code></pre>
<p>The goal here is to detect that the page refers to itself and then <code>exit</code> immediately to prevent the server from doing anything additional. Another option, and probably a good idea, is to log that this has happened so it shows up on a dashboard for evaluation.</p>
<p>Another way to attempt to detect this type of request on the server is by looking at the HTTP <code>Accept</code> header. All browsers except IE send different HTTP <code>Accept</code> headers for image requests than they do for HTML requests. As an example, Chrome sends the following <code>Accept</code> header for an HTML request:</p>
<pre><code>Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5</code></pre>
<p>Compare this to the <code>Accept</code> header that is sent for an image, script, or style sheet request:</p>
<pre><code>Accept: */*</code></pre>
<p>Firefox, Safari, and Opera all send roughly the same <code>Accept</code> header for HTML requests, meaning that you can check for an individual part, such as “text/html”, to determine if the request is an HTML request or something else. Unfortunately, IE only sends the latter <code>Accept</code> header for all requests, so there is no way to differentiate this on the server. For browsers other than IE, you can use something like the following:</p>
<pre><code>&lt;?php
    //Warning: Doesn't work for IE!

    //make sure the Accept header has 'text/htmnl' in it
    if (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false){
        exit;
    }
?&gt;</code></pre>
<p>This check is a little safer than the previous, but its big downside is that it doesn’t work in IE.</p>
<h2>Why does this happen?</h2>
<p>The real problem is the way that URI resolution is performed in browsers. This behavior is defined in <a href="http://tools.ietf.org/html/rfc3986">RFC 3986 &#8211; Uniform Resource Identifiers</a>. When an empty string is encountered as a URI, it’s considered a relative URI and is resolved according to the algorithm defined in <a href="http://tools.ietf.org/html/rfc3986#section-5.2">section 5.2</a>. This specific example, an empty string, is listed in <a href="http://tools.ietf.org/html/rfc3986#section-5.4">section 5.4</a>. Firefox, Safari, and Chrome are all resolving an empty string correctly per the specification, while Internet Explorer is resolving it incorrectly, apparently in line with an earlier version of the specification, <a href="http://tools.ietf.org/html/rfc2396">RFC 2396 &#8211; Uniform Resource Identifiers</a> (this was obsoleted by RFC 3986). So technically, the browsers are doing what they’re supposed to do to resolve relative URIs. The problem is that in this context, the empty string is clearly unintentional.</p>
<h2>It’s time to fix this</h2>
<p>This is a serious flaw in browsers, and I’m not sure you can look at it in any way where it’s not considered a bug. The inconsistent behavior, from Opera completely ignoring all invalid external references, to IE falling victim only for <code>&lt;img&gt;</code> tags while others do the same for <code>&lt;script&gt;</code> and <code>&lt;link&gt;</code> as well, seem to indicate a bug in browsers. Though browsers seem to be following correct URI resolution (except IE), I think this is a case where common sense must win over the letter of the specification. There is no way that an image can possibly render an HTML page, and the same goes for <code>&lt;script&gt;</code> and <code>&lt;link&gt;</code>. This bug has cost web developers hundreds of lost hours and has potentially brought down sites, pushing servers over capacity. Enough is enough. It’s time for the browser vendors to fix this bug. I’ve taken the liberty of filing or locating bugs:</p>
<ul>
<li>Firefox: <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=531327">Bug 531327</a></li>
<li>WebKit (Safari/Chrome): <a href="https://bugs.webkit.org/show_bug.cgi?id=30303">Bug 30303</a></li>
</ul>
<p>Please show support for fixing these bugs, as I don’t see any reason why we should still be dealing with this browser behavior. And if anyone can get the note to Microsoft so they can address IE, we’d all greatly appreciate it.</p>
<h2>HTML5 to the rescue</h2>
<p>HTML5 adds to the description of the <code>&lt;img&gt;</code> tag’s <code>src</code> attribute to instruct browsers not to make an additional request in <a href="http://www.w3.org/TR/html5/text-level-semantics.html#attr-img-src">section 4.8.2</a>:</p>
<blockquote><p>The <code>src</code> attribute must be present, and must contain a valid URL referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted. If the base URI of the element is the same as the document’s address, then the src attribute’s value must not be the empty string.</p>
</blockquote>
<p>Hopefully, browsers won’t have this problem in the future. Unfortunately, there is no such clause for <code>&lt;script src=""&gt;</code> and <code>&lt;link href=""&gt;</code>. Maybe there’s still time to make that adjustment to ensure browsers don’t accidentally implement this behavior.</p>
]]></content:encoded>
			<wfw:commentRss>http://witslog.com/wiki/technical/speed-up-a-website/empty-image-src-can-destroy-your-site/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>High Performance Ajax Applications</title>
		<link>http://witslog.com/wiki/technical/speed-up-a-website/high-performance-ajax-applications</link>
		<comments>http://witslog.com/wiki/technical/speed-up-a-website/high-performance-ajax-applications#comments</comments>
		<pubDate>Sun, 28 Mar 2010 11:10:02 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Speed up a website]]></category>

		<guid isPermaLink="false">http://witslog.com/wiki/?p=128</guid>
		<description><![CDATA[High Performance Ajax Applications
View more presentations from julien.lecomte.

]]></description>
			<content:encoded><![CDATA[<div style="width:425px" id="__ss_203896"><strong style="display:block;margin:12px 0 4px"><a href="http://www.slideshare.net/julien.lecomte/high-performance-ajax-applications" title="High Performance Ajax Applications">High Performance Ajax Applications</a></strong><object width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=high-performance-ajax-applications-1197671494632682-2&#038;rel=0&#038;stripped_title=high-performance-ajax-applications" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=high-performance-ajax-applications-1197671494632682-2&#038;rel=0&#038;stripped_title=high-performance-ajax-applications" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object>
<div style="padding:5px 0 12px">View more <a href="http://www.slideshare.net/">presentations</a> from <a href="http://www.slideshare.net/julien.lecomte">julien.lecomte</a>.</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://witslog.com/wiki/technical/speed-up-a-website/high-performance-ajax-applications/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Performance Research, Part 3: When the Cookie Crumbles</title>
		<link>http://witslog.com/wiki/technical/speed-up-a-website/performance-research-part-3-when-the-cookie-crumbles</link>
		<comments>http://witslog.com/wiki/technical/speed-up-a-website/performance-research-part-3-when-the-cookie-crumbles#comments</comments>
		<pubDate>Sun, 28 Mar 2010 10:28:25 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Speed up a website]]></category>

		<guid isPermaLink="false">http://witslog.com/wiki/?p=126</guid>
		<description><![CDATA[HTTP cookies are used for a variety of reasons such as authentication and personalization. Information about cookies is exchanged in the HTTP headers between web servers and browsers. This article discusses the impact of cookies on the overall user response time.
HTTP Quick Review
Cookies originate from...]]></description>
			<content:encoded><![CDATA[<p>HTTP cookies are used for a variety of reasons such as authentication and personalization. Information about cookies is exchanged in the HTTP headers between web servers and browsers. This article discusses the impact of cookies on the overall user response time.</p>
<h3 id="http-quick-review">HTTP Quick Review</h3>
<p>Cookies originate from web servers when browsers request a page. Here is a sample HTTP header sent by the web server after a request for <code>www.yahoo.com</code>:</p>
<pre>  HTTP/1.1 200 OK
  Content-Type: text/html; charset=utf-8
  Set-Cookie: C=abcde; path=/; domain=.yahoo.com
</pre>
<p>The header includes information about the response such as the protocol version, status code, and content-type. The <code>Set-Cookie</code> is also included in the response and in this example the name of the cookie is “C” and the value of the cookie is “abcde”. Note: The maximum size of a cookie is 5051 bytes in IE 6.0 and 4096 bytes in Firefox 1.5.</p>
<p>The browser saves the “C” cookie on the user’s computer and sends it back in future requests. The “<code>domain=.yahoo.com</code>” specifies that the browser should include the cookie in future requests within the <code>.yahoo.com</code> domain and all its sub-domains. For example, if the user then visits <code>finance.yahoo.com</code>, the browser includes the “C” cookie in the request. Since an Expires attribute is not included in this example, the cookie expires at the end of the session.</p>
<p>Here is a sample HTTP header for <code>finance.yahoo.com</code> sent by the browser:</p>
<pre>  GET / HTTP/1.1
  Host: finance.yahoo.com
  User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; ...
  Cookie: C=abcde;
</pre>
<p>Notice that the “C” cookie, originating from <code>www.yahoo.com</code>, is also included in the request for <code>finance.yahoo.com</code>.</p>
<h3 id="impact-on-response-time">Impact of cookies on response time</h3>
<p id="table1">The performance team at Yahoo! ran an experiment to measure the impact of retrieving a document with various cookie sizes. The experiment measured a static HTML document with no elements in the page. The primary variable in the experiment was the cookie size. We ran the experiment using a test harness that fetches a set of URLs repeatedly while measuring how long it takes to load the page on DSL. The results are shown in Table 1.</p>
<div class="figure" id="response-times-for-various-cookie-sizes-figure">
<table class="chart" id="response-times-for-various-cookie-sizes-table">
<caption>Table 1. Response times for various cookie sizes</caption>
<tbody>
<tr>
<th>Cookie Size</th>
<th>Median Response Time (Delta)</th>
</tr>
<tr>
<td>0 bytes</td>
<td>78 ms (<b>0 ms</b>)</td>
</tr>
<tr>
<td>500 bytes</td>
<td>79 ms (<b>+1 ms</b>)</td>
</tr>
<tr>
<td>1000 bytes</td>
<td>94 ms (<b>+16 ms</b>)</td>
</tr>
<tr>
<td>1500 bytes</td>
<td>109 ms (<b>+31 ms</b>)</td>
</tr>
<tr>
<td>2000 bytes</td>
<td>125 ms (<b>+47 ms</b>)</td>
</tr>
<tr>
<td>2500 bytes</td>
<td>141 ms (<b>+63 ms</b>)</td>
</tr>
<tr>
<td>3000 bytes</td>
<td>156 ms (<b>+78 ms</b>)</td>
</tr>
</tbody>
</table>
<p class="gloss"><strong>Note: </strong> Times are for page loads on DSL (~800 kbps).</p>
</div>
<p>These results highlight the importance of keeping the size of cookies as low as possible to minimize the impact on the user’s response time. A 3000 byte cookie, or multiple cookies that total 3000 bytes, could add as much as an 80 ms delay for users on DSL bandwidth speeds. The delay is even worse for users on dial-up.</p>
<h3 id="how-big-at-yahoo">How big are users’ cookies set at the .yahoo.com domain?</h3>
<p>Cookies set at the <code>.yahoo.com</code> domain affect the overall response time for users visiting web pages across the Yahoo! network. Figure 1 shows the percentages of Yahoo!’s total page views with various cookie sizes set at the <code>.yahoo.com</code> domain.</p>
<div class="chart">
<h4 id="percent-of-views-with-cookie-sizes"><strong>Figure 1.</strong> Percentage of Page Views with Various Cookie Sizes</h4>
<p><img src="http://www.yuiblog.com/assets/performance/cookies.gif" alt="Figure 1. Percentage of Page Views with Various Cookie Sizes" id="cookies" width="505" height="304"></p>
</div>
<p>About 80% of page views have fewer than 1000 bytes of cookies, which correlates to about a 5 to 15 ms delay for users on DSL bandwidth speeds. While the data shows that the majority of page views aren’t impacted by a significant delay, it also shows that about 2% of page views have over 1500 bytes of cookies set at the <code>.yahoo.com</code> domain. Although 2% sounds insignificant, at Yahoo! this translates to millions of page views per day, a compelling motivation for us to investigate this 2% and eliminate unnecessary cookies, reduce cookie sizes, and set cookies at more granualar domain levels.</p>
<p>In an earlier post about browser cache usage, one user made a <a href="http://yuiblog.com/blog/2007/01/04/performance-research-part-2/#comment-29021">comment</a> about the side-effects of different browsers. Since Internet Explorer and Firefox have different implementations for the maximum size and number of cookies supported, we also analyzed the data by browser type and found no significant difference between the cookie sizes. It would be interesting to further investigate whether there is a difference in performance across browsers.</p>
<h3 id="how-big-across-the-web">Analysis of Cookie Sizes across the Web</h3>
<p id="table2">To show how Yahoo!’s cookie usage relates to those of other companies, we analyzed the cookies set by other popular web sites. For this experiment, we cleared all our cookies and visited only the home pages of these web sites. Table 2 shows between 60 and 500 bytes of cookie information included in the HTTP headers.</p>
<div class="figure" id="total-cookie-sizes-figure">
<table class="chart" id="total-cookie-sizes-chart">
<caption>Table 2. Total Cookie Sizes</caption>
<tbody>
<tr>
<td>&nbsp;</td>
<th>Total Cookie Size</th>
</tr>
<tr>
<th><a href="http://www.amazon.com/">Amazon</a></th>
<td>60 bytes</td>
</tr>
<tr>
<th><a href="http://www.google.com/">Google</a></th>
<td>72 bytes</td>
</tr>
<tr>
<th><a href="http://www.yahoo.com/">Yahoo</a></th>
<td>122 bytes</td>
</tr>
<tr>
<th><a href="http://www.cnn.com/">CNN</a></th>
<td>184 bytes</td>
</tr>
<tr>
<th><a href="http://www.youtube.com/">YouTube</a></th>
<td>218 bytes</td>
</tr>
<tr>
<th><a href="http://www.msn.com/">MSN</a></th>
<td>268 bytes</td>
</tr>
<tr>
<th><a href="http://www.ebay.com/">eBay</a></th>
<td>331 bytes</td>
</tr>
<tr>
<th><a href="http://www.myspace.com/">MySpace</a></th>
<td>500 bytes</td>
</tr>
</tbody>
</table>
<p class="gloss"><strong>Note: </strong> We only requested the home page.</p>
</div>
<p>The data in Table 2 reflects only cookies set at the top domain levels to eliminate any cookies that may have been set by ads. The total cookie size for Yahoo! (122 bytes) in Table 2 differs from the cookie sizes indicated in Figure 4 because in this experiment we visited only the home pages of each web site. The data in Figure 4 reflect real users, many of whom visit multiple Yahoo! web pages. To illustrate, if <code>tv.yahoo.com</code> and <code>movies.yahoo.com</code> wanted to share information within a cookie, the cookie must be set at the <code>.yahoo.com</code> domain. The total cookie size set at the <code>.yahoo.com</code> domain for a user who visits multiple Yahoo! sub-domains is typically higher than the total cookie size set for a user who only visits <code>www.yahoo.com</code>.</p>
<p>Setting cookies at the appropriate path and domain is just as important as the size of the cookie, if not more. A cookie set at the <code>.yahoo.com</code> domain impacts the response time for every Yahoo! page in the <code>.yahoo.com</code> domain that a user visits.</p>
<h3 id="takeaways">Takeaways</h3>
<ul>
<li>Eliminate unnecessary cookies.</li>
<li>Keep cookie sizes as low as possible to minimize the impact on the user response time. </li>
<li>Be mindful of setting cookies at the appropriate domain level so other sub-domains are not affected.</li>
<li>Set an Expires date appropriately. An earlier Expires date or none removes the cookie sooner, improving the user response time.</li>
]]></content:encoded>
			<wfw:commentRss>http://witslog.com/wiki/technical/speed-up-a-website/performance-research-part-3-when-the-cookie-crumbles/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Best Practices for Speeding Up Your Web Site</title>
		<link>http://witslog.com/wiki/technical/speed-up-a-website/best-practices-for-speeding-up-your-web-site</link>
		<comments>http://witslog.com/wiki/technical/speed-up-a-website/best-practices-for-speeding-up-your-web-site#comments</comments>
		<pubDate>Sun, 28 Mar 2010 08:14:31 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Speed up a website]]></category>

		<guid isPermaLink="false">http://witslog.com/wiki/?p=121</guid>
		<description><![CDATA[Minimize HTTP Requests
tag: content
80% of the end-user response time is spent on the front-end. Most of this time is tied up in downloading all the components in the page: images, stylesheets, scripts, Flash, etc. Reducing the number of components in turn reduces the number of...]]></description>
			<content:encoded><![CDATA[<h3 id="num_http">Minimize HTTP Requests</h3>
<p class="date">tag: content</p>
<p>80% of the end-user response time is spent on the front-end. Most of this time is tied up in downloading all the components in the page: images, stylesheets, scripts, Flash, etc. Reducing the number of components in turn reduces the number of HTTP requests required to render the page. This is the key to faster pages. </p>
<p>One way to reduce the number of components in the page is to simplify the page&#8217;s design. But is there a way to build pages with richer content while also achieving fast response times? Here are some techniques for reducing the number of HTTP requests, while still supporting rich page designs.</p>
<p><strong>Combined files</strong> are a way to reduce the number of HTTP requests by combining all scripts into a single script, and similarly combining all CSS into a single stylesheet. Combining files is more challenging when the scripts and stylesheets vary from page to page, but making this part of your release process improves response times.</p>
<p><a href="http://alistapart.com/articles/sprites"><strong>CSS Sprites</strong></a> are the preferred method for reducing the number of image requests. Combine your background images into a single image and use the CSS <code>background-image</code> and <code>background-position</code> properties to display the desired image segment.</p>
<p><a href="http://www.w3.org/TR/html401/struct/objects.html#h-13.6"><strong>Image maps</strong></a> combine multiple images into a single image. The overall size is about the same, but reducing the number of HTTP requests speeds up the page. Image maps only work if the images are contiguous in the page, such as a navigation bar. Defining the coordinates of image maps can be tedious and error prone. Using image maps for navigation is not accessible too, so it&#8217;s not recommended.</p>
<p><strong>Inline images</strong> use the <a href="http://tools.ietf.org/html/rfc2397"><code>data:</code> URL scheme</a> to embed the image data in the actual page. This can increase the size of your HTML document. Combining inline images into your (cached) stylesheets is a way to reduce HTTP requests and avoid increasing the size of your pages. Inline images are not yet supported across all major browsers.</p>
<p>Reducing the number of HTTP requests in your page is the place to start. This is the most important guideline for improving performance for first time visitors. As described in Tenni Theurer&#8217;s blog post <a href="http://yuiblog.com/blog/2007/01/04/performance-research-part-2/">Browser Cache Usage &#8211; Exposed!</a>, 40-60% of daily visitors to your site come in with an empty cache. Making your page fast for these first time visitors is key to a better user experience.</p>
<p><a href="#page-nav">top</a> | <a href="http://developer.yahoo.net/blog/archives/2007/04/rule_1_make_few.html">discuss this rule</a></p>
<h3 id="cdn">Use a Content Delivery Network</h3>
<p class="date">tag: server</p>
<p>The user&#8217;s proximity to your web server has an impact on response times. Deploying your content across multiple, geographically dispersed servers will make your pages load faster from the user&#8217;s perspective. But where should you start?</p>
<p>As a first step to implementing geographically dispersed content, don&#8217;t attempt to redesign your web application to work in a distributed architecture. Depending on the application, changing the architecture could include daunting tasks such as synchronizing session state and replicating database transactions across server locations. Attempts to reduce the distance between users and your content could be delayed by, or never pass, this application architecture step. </p>
<p>Remember that 80-90% of the end-user response time is spent downloading all the components in the page: images, stylesheets, scripts, Flash, etc. This is the <em>Performance Golden Rule</em>. Rather than starting with the difficult task of redesigning your application architecture, it&#8217;s better to first disperse your static content. This not only achieves a bigger reduction in response times, but it&#8217;s easier thanks to content delivery networks.</p>
<p>A content delivery network (CDN) is a collection of web servers distributed across multiple locations to deliver content more efficiently to users. The server selected for delivering content to a specific user is typically based on a measure of network proximity. For example, the server with the fewest network hops or the server with the quickest response time is chosen.</p>
<p>Some large Internet companies own their own CDN, but it&#8217;s cost-effective to use a CDN service provider, such as <a href="http://www.akamai.com/">Akamai Technologies</a>, <a href="http://www.mirror-image.com/">Mirror Image Internet</a>, or <a href="http://www.limelightnetworks.com/">Limelight Networks</a>. For start-up companies and private web sites, the cost of a CDN service can be prohibitive, but as your target audience grows larger and becomes more global, a CDN is necessary to achieve fast response times. At Yahoo!, properties that moved static content off their application web servers to a CDN improved end-user response times by 20% or more. Switching to a CDN is a relatively easy code change that will dramatically improve the speed of your web site.</p>
<p><a href="#page-nav">top</a> | <a href="http://developer.yahoo.net/blog/archives/2007/04/high_performanc_1.html">discuss this rule</a></p>
<h3 id="expires">Add an Expires or a Cache-Control Header</h3>
<p class="date">tag: server</p>
<p>There are two aspects to this rule:</p>
<ul>
<li class="bullist">For static components: implement &#8220;Never expire&#8221; policy by setting far future <code>Expires</code> header</li>
<li class="bullist">For dynamic components: use an appropriate <code>Cache-Control</code> header to help the browser with conditional requests</li>
</ul>
<p></p>
<p>Web page designs are getting richer and richer, which means more scripts, stylesheets, images, and Flash in the page. A first-time visitor to your page may have to make several HTTP requests, but by using the Expires header you make those components cacheable. This avoids unnecessary HTTP requests on subsequent page views. Expires headers are most often used with images, but they should be used on <em>all</em> components including scripts, stylesheets, and Flash components.</p>
<p>Browsers (and proxies) use a cache to reduce the number and size of HTTP requests, making web pages load faster. A web server uses the Expires header in the HTTP response to tell the client how long a component can be cached. This is a far future Expires header, telling the browser that this response won&#8217;t be stale until April 15, 2010. </p>
<pre>      Expires: Thu, 15 Apr 2010 20:00:00 GMT</pre>
<p></p>
<p>If your server is Apache, use the ExpiresDefault directive to set an expiration date relative to the current date. This example of the ExpiresDefault directive sets the Expires date 10 years out from the time of the request.</p>
<pre>      ExpiresDefault "access plus 10 years"</pre>
<p></p>
<p>Keep in mind, if you use a far future Expires header you have to change the component&#8217;s filename whenever the component changes. At Yahoo! we often make this step part of the build process: a version number is embedded in the component&#8217;s filename, for example, yahoo_2.0.6.js.</p>
<p>Using a far future Expires header affects page views only after a user has already visited your site. It has no effect on the number of HTTP requests when a user visits your site for the first time and the browser&#8217;s cache is empty. Therefore the impact of this performance improvement depends on how often users hit your pages with a primed cache. (A &#8220;primed cache&#8221; already contains all of the components in the page.) We <a href="http://yuiblog.com/blog/2007/01/04/performance-research-part-2/">measured this at Yahoo!</a> and found the number of page views with a primed cache is 75-85%. By using a far future Expires header, you increase the number of components that are cached by the browser and re-used on subsequent page views without sending a single byte over the user&#8217;s Internet connection.</p>
<p><a href="#page-nav">top</a> | <a href="http://developer.yahoo.net/blog/archives/2007/05/high_performanc_2.html">discuss this rule</a></p>
<h3 id="gzip">Gzip Components</h3>
<p class="date">tag: server</p>
<p>The time it takes to transfer an HTTP request and response across the network can be significantly reduced by decisions made by front-end engineers. It&#8217;s true that the end-user&#8217;s bandwidth speed, Internet service provider, proximity to peering exchange points, etc. are beyond the control of the development team. But there are other variables that affect response times. Compression reduces response times by reducing the size of the HTTP response.</p>
<p>Starting with HTTP/1.1, web clients indicate support for compression with the Accept-Encoding header in the HTTP request.</p>
<pre>      Accept-Encoding: gzip, deflate</pre>
<p></p>
<p>If the web server sees this header in the request, it may compress the response using one of the methods listed by the client. The web server notifies the web client of this via the Content-Encoding header in the response.</p>
<pre>      Content-Encoding: gzip</pre>
<p></p>
<p>Gzip is the most popular and effective compression method at this time. It was developed by the GNU project and standardized by <a href="http://www.ietf.org/rfc/rfc1952.txt">RFC 1952</a>. The only other compression format you&#8217;re likely to see is deflate, but it&#8217;s less effective and less popular. </p>
<p>Gzipping generally reduces the response size by about 70%. Approximately 90% of today&#8217;s Internet traffic travels through browsers that claim to support gzip. If you use Apache, the module configuring gzip depends on your version: Apache 1.3 uses <a href="http://sourceforge.net/projects/mod-gzip/">mod_gzip</a> while Apache 2.x uses <a href="http://httpd.apache.org/docs/2.0/mod/mod_deflate.html">mod_deflate</a>. </p>
<p>There are known issues with browsers and proxies that may cause a mismatch in what the browser expects and what it receives with regard to compressed content. Fortunately, these edge cases are dwindling as the use of older browsers drops off. The Apache modules help out by adding appropriate Vary response headers automatically. </p>
<p>Servers choose what to gzip based on file type, but are typically too limited in what they decide to compress. Most web sites gzip their HTML documents. It&#8217;s also worthwhile to gzip your scripts and stylesheets, but many web sites miss this opportunity. In fact, it&#8217;s worthwhile to compress any text response including XML and JSON. Image and PDF files should not be gzipped because they are already compressed. Trying to gzip them not only wastes CPU but can potentially increase file sizes. </p>
<p>Gzipping as many file types as possible is an easy way to reduce page weight and accelerate the user experience.</p>
<p><a href="#page-nav">top</a> | <a href="http://developer.yahoo.net/blog/archives/2007/07/high_performanc_3.html">discuss this rule</a></p>
<h3 id="css_top">Put Stylesheets at the Top</h3>
<p class="date">tag: css</p>
<p>While researching performance at Yahoo!, we discovered that moving stylesheets to the document HEAD makes pages <em>appear</em> to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively. </p>
<p>Front-end engineers that care about performance want a page to load progressively; that is, we want the browser to display whatever content it has as soon as possible. This is especially important for pages with a lot of content and for users on slower Internet connections. The importance of giving users visual feedback, such as progress indicators, has been well researched and <a href="http://www.useit.com/papers/responsetime.html">documented</a>. In our case the HTML page is the progress indicator! When the browser loads the page progressively the header, the navigation bar, the logo at the top, etc. all serve as visual feedback for the user who is waiting for the page. This improves the overall user experience.</p>
<p>The problem with putting stylesheets near the bottom of the document is that it prohibits progressive rendering in many browsers, including Internet Explorer. These browsers block rendering to avoid having to redraw elements of the page if their styles change. The user is stuck viewing a blank white page.</p>
<p>The <a href="http://www.w3.org/TR/html4/struct/links.html#h-12.3">HTML specification</a> clearly states that stylesheets are to be included in the HEAD of the page: &#8220;Unlike A, [LINK] may only appear in the HEAD section of a document, although it may appear any number of times.&#8221; Neither of the alternatives, the blank white screen or flash of unstyled content, are worth the risk. The optimal solution is to follow the HTML specification and load your stylesheets in the document HEAD.</p>
<p><a href="#page-nav">top</a> | <a href="http://developer.yahoo.net/blog/archives/2007/07/high_performanc_4.html">discuss this rule</a></p>
<h3 id="js_bottom">Put Scripts at the Bottom</h3>
<p class="date">tag: javascript</p>
<p>The problem caused by scripts is that they block parallel downloads. The <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.1.4">HTTP/1.1 specification</a> suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won&#8217;t start any other downloads, even on different hostnames. </p>
<p>In some situations it&#8217;s not easy to move scripts to the bottom. If, for example, the script uses <code>document.write</code> to insert part of the page&#8217;s content, it can&#8217;t be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.</p>
<p>An alternative suggestion that often comes up is to use deferred scripts. The <code>DEFER</code> attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn&#8217;t support the <code>DEFER</code> attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.</p>
<p><a href="#page-nav">top</a> | <a href="http://developer.yahoo.net/blog/archives/2007/07/high_performanc_5.html">discuss this rule</a></p>
<h3 id="css_expressions">Avoid CSS Expressions</h3>
<p class="date">tag: css</p>
<p>CSS expressions are a powerful (and dangerous) way to set CSS properties dynamically. They&#8217;re supported in Internet Explorer, starting with <a href="http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp">version 5</a>. As an example, the background color could be set to alternate every hour using CSS expressions.</p>
<pre>      background-color: expression( (new Date()).getHours()%2 ? "#B8D4FF" : "#F08A00" );</pre>
<p></p>
<p>As shown here, the <code>expression</code> method accepts a JavaScript expression. The CSS property is set to the result of evaluating the JavaScript expression. The <code>expression</code> method is ignored by other browsers, so it is useful for setting properties in Internet Explorer needed to create a consistent experience across browsers.</p>
<p>The problem with expressions is that they are evaluated more frequently than most people expect. Not only are they evaluated when the page is rendered and resized, but also when the page is scrolled and even when the user moves the mouse over the page. Adding a counter to the CSS expression allows us to keep track of when and how often a CSS expression is evaluated. Moving the mouse around the page can easily generate more than 10,000 evaluations.</p>
<p>One way to reduce the number of times your CSS expression is evaluated is to use one-time expressions, where the first time the expression is evaluated it sets the style property to an explicit value, which replaces the CSS expression. If the style property must be set dynamically throughout the life of the page, using event handlers instead of CSS expressions is an alternative approach. If you must use CSS expressions, remember that they may be evaluated thousands of times and could affect the performance of your page.</p>
<p><a href="#page-nav">top</a> | <a href="http://developer.yahoo.net/blog/archives/2007/07/high_performanc_6.html">discuss this rule</a></p>
<h3 id="external">Make JavaScript and CSS External</h3>
<p class="date">tag: javascript, css</p>
<p>Many of these performance rules deal with how external components are managed. However, before these considerations arise you should ask a more basic question: Should JavaScript and CSS be contained in external files, or inlined in the page itself?</p>
<p>Using external files in the real world generally produces faster pages because the JavaScript and CSS files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the size of the HTML document is reduced without increasing the number of HTTP requests. </p>
<p>The key factor, then, is the frequency with which external JavaScript and CSS components are cached relative to the number of HTML documents requested. This factor, although difficult to quantify, can be gauged using various metrics. If users on your site have multiple page views per session and many of your pages re-use the same scripts and stylesheets, there is a greater potential benefit from cached external files. </p>
<p>Many web sites fall in the middle of these metrics. For these sites, the best solution generally is to deploy the JavaScript and CSS as external files. The only exception where inlining is preferable is with home pages, such as <a href="http://www.yahoo.com">Yahoo!&#8217;s front page</a> and <a href="http://my.yahoo.com">My Yahoo!</a>.<br />
Home pages that have few (perhaps only one) page view per session may find that inlining JavaScript and CSS results in faster end-user response times.</p>
<p>For front pages that are typically the first of many page views, there are techniques that leverage the reduction of HTTP requests that inlining provides, as well as the caching benefits achieved through using external files. One such technique is to inline JavaScript and CSS in the front page, but dynamically download the external files after the page has finished loading. Subsequent pages would reference the external files that should already be in the browser&#8217;s cache.</p>
<p><a href="#page-nav">top</a> | <a href="http://developer.yahoo.net/blog/archives/2007/07/rule_8_make_jav.html">discuss this rule</a></p>
<h3 id="dns_lookups">Reduce DNS Lookups</h3>
<p class="date">tag: content</p>
<p>The Domain Name System (DNS) maps hostnames to IP addresses, just as phonebooks map people&#8217;s names to their phone numbers. When you type www.yahoo.com into your browser, a DNS resolver contacted by the browser returns that server&#8217;s IP address. DNS has a cost. It typically takes 20-120 milliseconds for DNS to lookup the IP address for a given hostname. The browser can&#8217;t download anything from this hostname until the DNS lookup is completed. </p>
<p>DNS lookups are cached for better performance. This caching can occur on a special caching server, maintained by the user&#8217;s ISP or local area network, but there is also caching that occurs on the individual user&#8217;s computer. The DNS information remains in the operating system&#8217;s DNS cache (the &#8220;DNS Client service&#8221; on Microsoft Windows). Most browsers have their own caches, separate from the operating system&#8217;s cache. As long as the browser keeps a DNS record in its own cache, it doesn&#8217;t bother the operating system with a request for the record.</p>
<p>Internet Explorer caches DNS lookups for 30 minutes by default, as specified by the  <code>DnsCacheTimeout</code> registry setting. Firefox caches DNS lookups for 1 minute, controlled by the <code>network.dnsCacheExpiration</code> configuration setting. (Fasterfox changes this to 1 hour.)</p>
<p>When the client&#8217;s DNS cache is empty (for both the browser and the operating system), the number of DNS lookups is equal to the number of unique hostnames in the web page. This includes the hostnames used in the page&#8217;s URL, images, script files, stylesheets, Flash objects, etc. Reducing the number of unique hostnames reduces the number of DNS lookups. </p>
<p>Reducing the number of unique hostnames has the potential to reduce the amount of parallel downloading that takes place in the page. Avoiding DNS lookups cuts response times, but reducing parallel downloads may increase response times. My guideline is to split these components across at least two but no more than four hostnames. This results in a good compromise between reducing DNS lookups and allowing a high degree of parallel downloads.</p>
<p><a href="#page-nav">top</a> | <a href="http://developer.yahoo.net/blog/archives/2007/07/high_performanc_7.html">discuss this rule</a></p>
<h3 id="minify">Minify JavaScript and CSS</h3>
<p class="date">tag: javascript, css</p>
<p>Minification is the practice of removing unnecessary characters from code to reduce its size thereby improving load times. When code is minified all comments are removed, as well as unneeded white space characters (space, newline, and tab). In the case of JavaScript, this improves response time performance because the size of the downloaded file is reduced. Two popular tools for minifying JavaScript code are <a href="http://crockford.com/javascript/jsmin">JSMin</a> and <a href="http://developer.yahoo.com/yui/compressor/">YUI Compressor</a>. The YUI compressor can also minify CSS.</p>
<p>Obfuscation is an alternative optimization that can be applied to source code. It&#8217;s more complex than minification and thus more likely to generate bugs as a result of the obfuscation step itself. In a survey of ten top U.S. web sites, minification achieved a 21% size reduction versus 25% for obfuscation. Although obfuscation has a higher size reduction, minifying JavaScript is less risky.</p>
<p>In addition to minifying external scripts and styles, inlined <code>&lt;script&gt;</code> and <code>&lt;style&gt;</code> blocks can and should also be minified. Even if you gzip your scripts and styles, minifying them will still reduce the size by 5% or more. As the use and size of JavaScript and CSS increases, so will the savings gained by minifying your code.</p>
<p><a href="#page-nav">top</a> | <a href="http://developer.yahoo.net/blog/archives/2007/07/high_performanc_8.html">discuss this rule</a></p>
<h3 id="redirects">Avoid Redirects</h3>
<p class="date">tag: content</p>
<p>Redirects are accomplished using the 301 and 302 status codes. Here&#8217;s an example of the HTTP headers in a 301 response:</p>
<pre>      HTTP/1.1 301 Moved Permanently
      Location: http://example.com/newuri
      Content-Type: text/html</pre>
<p></p>
<p>The browser automatically takes the user to the URL specified in the <code>Location</code> field. All the information necessary for a redirect is in the headers. The body of the response is typically empty. Despite their names, neither a 301 nor a 302 response is cached in practice unless additional headers, such as <code>Expires</code> or <code>Cache-Control</code>, indicate it should be. The meta refresh tag and JavaScript are other ways to direct users to a different URL, but if you must do a redirect, the preferred technique is to use the standard 3xx HTTP status codes, primarily to ensure the back button works correctly.</p>
<p>The main thing to remember is that redirects slow down the user experience. Inserting a redirect between the user and the HTML document delays everything in the page since nothing in the page can be rendered and no components can start being downloaded until the HTML document has arrived.</p>
<p>One of the most wasteful redirects happens frequently and web developers are generally not aware of it. It occurs when a trailing slash (/) is missing from a URL that should otherwise have one. For example, going to <a href="http://astrology.yahoo.com/astrology">http://astrology.yahoo.com/astrology</a> results in a 301 response containing a redirect to <a href="http://astrology.yahoo.com/astrology/">http://astrology.yahoo.com/astrology/</a> (notice the added trailing slash). This is fixed in Apache by using <code>Alias</code> or <code>mod_rewrite</code>, or the <code>DirectorySlash</code> directive if you&#8217;re using Apache handlers.</p>
<p>Connecting an old web site to a new one is another common use for redirects. Others include connecting different parts of a website and directing the user based on certain conditions (type of browser, type of user account, etc.). Using a redirect to connect two web sites is simple and requires little additional coding. Although using redirects in these situations reduces the complexity for developers, it degrades the user experience. Alternatives for this use of redirects include using <code>Alias</code> and <code>mod_rewrite</code> if the two code paths are hosted on the same server. If a domain name change is the cause of using redirects, an alternative is to create a CNAME (a DNS record that creates an alias pointing from one domain name to another) in combination with <code>Alias</code> or <code>mod_rewrite</code>.</p>
<p><a href="#page-nav">top</a> | <a href="http://developer.yahoo.net/blog/archives/2007/07/high_performanc_9.html">discuss this rule</a></p>
<h3 id="js_dupes">Remove Duplicate Scripts</h3>
<p class="date">tag: javascript</p>
<p>It hurts performance to include the same JavaScript file twice in one page. This isn&#8217;t as unusual as you might think. A review of the ten top U.S. web sites shows that two of them contain a duplicated script. Two main factors increase the odds of a script being duplicated in a single web page: team size and number of scripts. When it does happen, duplicate scripts hurt performance by creating unnecessary HTTP requests and wasted JavaScript execution.</p>
<p>Unnecessary HTTP requests happen in Internet Explorer, but not in Firefox. In Internet Explorer, if an external script is included twice and is not cacheable, it generates two HTTP requests during page loading. Even if the script is cacheable, extra HTTP requests occur when the user reloads the page.</p>
<p>In addition to generating wasteful HTTP requests, time is wasted evaluating the script multiple times. This redundant JavaScript execution happens in both Firefox and Internet Explorer, regardless of whether the script is cacheable.</p>
<p>One way to avoid accidentally including the same script twice is to implement a script management module in your templating system. The typical way to include a script is to use the SCRIPT tag in your HTML page.</p>
<pre>      &lt;script type="text/javascript" src="menu_1.0.17.js"&gt;&lt;/script&gt;</pre>
<p></p>
<p>An alternative in PHP would be to create a function called <code>insertScript</code>.</p>
<pre>      &lt;?php insertScript("menu.js") ?&gt;</pre>
<p></p>
<p>In addition to preventing the same script from being inserted multiple times, this function could handle other issues with scripts, such as dependency checking and adding version numbers to script filenames to support far future Expires headers.</p>
<p><a href="#page-nav">top</a> | <a href="http://developer.yahoo.net/blog/archives/2007/07/high_performanc_10.html">discuss this rule</a></p>
<h3 id="etags">Configure ETags</h3>
<p class="date">tag: server</p>
<p>Entity tags (ETags) are a mechanism that web servers and browsers use to determine whether the component in the browser&#8217;s cache matches the one on the origin server. (An &#8220;entity&#8221; is another word a &#8220;component&#8221;: images, scripts, stylesheets, etc.) ETags were added to provide a mechanism for validating entities that is more flexible than the last-modified date. An ETag is a string that uniquely identifies a specific version of a component. The only format constraints are that the string be quoted. The origin server specifies the component&#8217;s ETag using the <code>ETag</code> response header.</p>
<pre>      HTTP/1.1 200 OK
      Last-Modified: Tue, 12 Dec 2006 03:03:59 GMT
      ETag: "10c24bc-4ab-457e1c1f"
      Content-Length: 12195</pre>
<p></p>
<p>Later, if the browser has to validate a component, it uses the <code>If-None-Match</code> header to pass the ETag back to the origin server. If the ETags match, a 304 status code is returned reducing the response by 12195 bytes for this example.
</p>
<pre>      GET /i/yahoo.gif HTTP/1.1
      Host: us.yimg.com
      If-Modified-Since: Tue, 12 Dec 2006 03:03:59 GMT
      If-None-Match: "10c24bc-4ab-457e1c1f"
      HTTP/1.1 304 Not Modified</pre>
<p></p>
<p>The problem with ETags is that they typically are constructed using attributes that make them unique to a specific server hosting a site. ETags won&#8217;t match when a browser gets the original component from one server and later tries to validate that component on a different server, a situation that is all too common on Web sites that use a cluster of servers to handle requests. By default, both Apache and IIS embed data in the ETag that dramatically reduces the odds of the validity test succeeding on web sites with multiple servers.
</p>
<p>The ETag format for Apache 1.3 and 2.x is <code>inode-size-timestamp</code>. Although a given file may reside in the same directory across multiple servers, and have the same file size, permissions, timestamp, etc., its inode is different from one server to the next.
</p>
<p>IIS 5.0 and 6.0 have a similar issue with ETags. The format for ETags on IIS is <code>Filetimestamp:ChangeNumber</code>. A <code>ChangeNumber</code> is a counter used to track configuration changes to IIS. It&#8217;s unlikely that the <code>ChangeNumber</code> is the same across all IIS servers behind a web site.
</p>
<p>The end result is ETags generated by Apache and IIS for the exact same component won&#8217;t match from one server to another. If the ETags don&#8217;t match, the user doesn&#8217;t receive the small, fast 304 response that ETags were designed for; instead, they&#8217;ll get a normal 200 response along with all the data for the component. If you host your web site on just one server, this isn&#8217;t a problem. But if you have multiple servers hosting your web site, and you&#8217;re using Apache or IIS with the default ETag configuration, your users are getting slower pages, your servers have a higher load, you&#8217;re consuming greater bandwidth, and proxies aren&#8217;t caching your content efficiently. Even if your components have a far future <code>Expires</code> header, a conditional GET request is still made whenever the user hits Reload or Refresh.</p>
<p>If you&#8217;re not taking advantage of the flexible validation model that ETags provide, it&#8217;s better to just remove the ETag altogether. The <code>Last-Modified</code> header validates based on the component&#8217;s timestamp. And removing the ETag reduces the size of the HTTP headers in both the response and subsequent requests. This <a href="http://support.microsoft.com/?id=922733">Microsoft Support article</a> describes how to remove ETags. In Apache, this is done by simply adding the following line to your Apache configuration file:
</p>
<pre>      FileETag none</pre>
<p></p>
<p><a href="#page-nav">top</a> | <a href="http://developer.yahoo.net/blog/archives/2007/07/high_performanc_11.html">discuss this rule</a></p>
<h3 id="cacheajax">Make Ajax Cacheable</h3>
<p class="date">tag: content</p>
<p>One of the cited benefits of Ajax is that it provides instantaneous feedback to the user because it requests information asynchronously from the backend web server. However, using Ajax is no guarantee that the user won&#8217;t be twiddling his thumbs waiting for those asynchronous JavaScript and XML responses to return. In many applications, whether or not the user is kept waiting depends on how Ajax is used. For example, in a web-based email client the user will be kept waiting for the results of an Ajax request to find all the email messages that match their search criteria. It&#8217;s important to remember that &#8220;asynchronous&#8221; does not imply &#8220;instantaneous&#8221;.</p>
<p>To improve performance, it&#8217;s important to optimize these Ajax responses. The most important way to improve the performance of Ajax is to make the responses cacheable, as discussed in <a href="#expires">Add an Expires or a Cache-Control Header</a>. Some of the other rules also apply to Ajax:</p>
<ul>
<li class="bullist"> <a href="#gzip">Gzip Components</a>
</li>
<li class="bullist"> <a href="#dns_lookups">Reduce DNS Lookups</a>
  </li>
<li class="bullist"> <a href="#minify">Minify JavaScript</a>
  </li>
<li class="bullist"> <a href="#redirects">Avoid Redirects</a>
  </li>
<li class="bullist"> <a href="#etags">Configure ETags</a>
</li>
</ul>
<p></p>
<p>Let&#8217;s look at an example. A Web 2.0 email client might use Ajax to download the user&#8217;s address book for autocompletion. If the user hasn&#8217;t modified her address book since the last time she used the email web app, the previous address book response could be read from cache if that Ajax response was made cacheable with a future Expires or Cache-Control header. The browser must be informed when to use a previously cached address book response versus requesting a new one. This could be done by adding a timestamp to the address book Ajax URL indicating the last time the user modified her address book, for example, <code>&amp;t=1190241612</code>. If the address book hasn&#8217;t been modified since the last download, the timestamp will be the same and the address book will be read from the browser&#8217;s cache eliminating an extra HTTP roundtrip. If the user has modified her address book, the timestamp ensures the new URL doesn&#8217;t match the cached response, and the browser will request the updated address book entries.</p>
<p>Even though your Ajax responses are created dynamically, and might only be applicable to a single user, they can still be cached. Doing so will make your Web 2.0 apps faster.</p>
<p><a href="#page-nav">top</a> | <a href="http://developer.yahoo.net/blog/archives/2007/09/high_performanc_12.html">discuss this rule</a></p>
<h3 id="flush">Flush the Buffer Early</h3>
<p class="date">tag: server</p>
<p>
 When users request a page, it can take anywhere from 200 to 500ms for the backend server to stitch together the HTML page.<br />
 During this time, the browser is idle as it waits for the data to arrive.<br />
 In PHP you have the function <a href="http://php.net/flush">flush()</a>.<br />
 It allows you to send your partially ready HTML response to the browser so that<br />
 the browser can start fetching components while your backend is busy with the rest of the HTML page.<br />
 The benefit is mainly seen on busy backends or light frontends.
</p>
<p>
    A good place to consider flushing is right after the HEAD because the HTML for the head is<br />
    usually easier to produce and it allows you to include any CSS and JavaScript<br />
    files for the browser to start fetching in parallel while the backend is still processing.</p>
<p>Example:</p>
<pre>      ... &lt;!-- css, js --&gt;

    &lt;/head&gt;
    <span class="hilite">&lt;?php flush(); ?&gt;</span>
    &lt;body&gt;
      ... &lt;!-- content --&gt;
</pre>
<p></p>
<p><a href="http://search.yahoo.com">Yahoo! search</a> pioneered research and real user testing to prove the benefits of using this technique.</p>
<p><a href="#page-nav">top</a></p>
<h3 id="ajax_get">Use GET for AJAX Requests</h3>
<p class="date">tag: server</p>
<p>
    The <a href="http://mail.yahoo.com">Yahoo! Mail</a> team found that when using <code>XMLHttpRequest</code>, POST is implemented in the browsers as a two-step process:<br />
    sending the headers first, then sending data. So it&#8217;s best to use GET, which only takes one TCP packet to send (unless you have a lot of cookies).<br />
    The maximum URL length in IE is 2K, so if you send more than 2K data you might not be able to use GET.</p>
<p>An interesting side affect is that POST without actually posting any data behaves like GET.<br />
Based on the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">HTTP specs</a>, GET is meant for retrieving information, so it<br />
        makes sense (semantically) to use GET when you&#8217;re only requesting data, as opposed to sending data to be stored server-side.
</p>
<p><a href="#page-nav">top</a></p>
<h3 id="postload">Post-load Components</h3>
<p class="date">tag: content</p>
<p>
    You can take a closer look at your page and ask yourself: &#8220;What&#8217;s absolutely required in order to render the page initially?&#8221;.<br />
    The rest of the content and components can wait.
</p>
<p>
    JavaScript is an ideal candidate for splitting before and after the onload event. For example<br />
    if you have JavaScript code and libraries that do drag and drop and animations, those can wait,<br />
    because dragging elements on the page comes after the initial rendering.<br />
    Other places to look for candidates for post-loading include hidden content (content that appears after a user action) and images below the fold.
</p>
<p>
    Tools to help you out in your effort: <a href="http://developer.yahoo.com/yui/imageloader/">YUI Image Loader</a> allows you to delay images<br />
    below the fold and the <a href="http://developer.yahoo.com/yui/get/">YUI Get utility</a> is an easy way to include JS and CSS on the fly.<br />
    For an example in the wild take a look at <a href="http://www.yahoo.com">Yahoo! Home Page</a> with Firebug&#8217;s Net Panel turned on.</p>
<p>
    It&#8217;s good when the performance goals are inline with other<br />
    web development best practices. In this case, the idea of progressive enhancement tells us that JavaScript, when supported, can<br />
    improve the user experience but you have to make sure the page works even without JavaScript. So after you&#8217;ve made sure the page<br />
    works fine, you can enhance it with some post-loaded scripts that give you more bells and whistles such as drag and drop and animations.
</p>
<p><a href="#page-nav">top</a></p>
<h3 id="preload">Preload Components</h3>
<p class="date">tag: content</p>
<p>
    Preload may look like the opposite of post-load, but it actually has a different goal.<br />
    By preloading components you can take advantage of the time the browser is idle and request components<br />
    (like images, styles and scripts) you&#8217;ll need in the future.<br />
    This way when the user visits the next page, you could have most of the components already in<br />
    the cache and your page will load much faster for the user.</p>
<p>
    There are actually several types of preloading:
</p>
<ul>
<li class="bullist"><em>Unconditional</em> preload &#8211; as soon as onload fires, you go ahead and fetch some extra components.<br />
        Check google.com for an example of how a sprite image is requested onload. This sprite image is<br />
        not needed on the google.com homepage, but it is needed on the consecutive search result page.</li>
<li class="bullist"><em>Conditional</em> preload &#8211; based on a user action you make an educated guess where the user is headed next and preload accordingly.<br />
        On <a href="http://search.yahoo.com">search.yahoo.com</a> you can see how some extra components are requested<br />
        after you start typing in the input box.</li>
<li class="bullist"><em>Anticipated</em> preload &#8211; preload in advance before launching a redesign. It often happens after a redesign that you hear:<br />
        &#8220;The new site is cool, but it&#8217;s slower than before&#8221;. Part of the problem could be that the users were visiting your old site with a<br />
        full cache, but the new one is always an empty cache experience. You can mitigate this side effect by preloading some<br />
        components before you even launched the redesign. Your old site can use the time the browser is idle and request images and scripts<br />
        that will be used by the new site</li>
</ul>
<p><a href="#page-nav">top</a></p>
<h3 id="min_dom">Reduce the Number of DOM Elements</h3>
<p class="date">tag: content</p>
<p>
    A complex page means more bytes to download and it also means slower DOM access in JavaScript. It makes a difference<br />
    if you loop through 500 or 5000 DOM elements on the page when you want to add an event handler for example.
</p>
<p>
    A high number of DOM elements can be a symptom that there&#8217;s something that should be improved with the markup<br />
    of the page without necessarily removing content.<br />
    Are you using nested tables for layout purposes?<br />
    Are you throwing in more <code>&lt;div&gt;</code>s only to fix layout issues?<br />
    Maybe there&#8217;s a better and more semantically correct way to do your markup.
</p>
<p>
    A great help with layouts are the <a href="http://developer.yahoo.com/yui/">YUI CSS utilities</a>:<br />
    grids.css can help you with the overall layout, fonts.css and reset.css<br />
    can help you strip away the browser&#8217;s defaults formatting.<br />
    This is a chance to start fresh and think about your markup,<br />
    for example use <code>&lt;div&gt;</code>s only when it makes sense semantically, and not because it renders a new line.</p>
<p>
    The number of DOM elements is easy to test, just type in Firebug&#8217;s console:<br />
        <code>document.getElementsByTagName('*').length</code>
</p>
<p>
    And how many DOM elements are too many? Check other similar pages that have good markup.<br />
    For example the <a href="http://www.yahoo.com">Yahoo! Home Page</a> is a pretty busy page and still under 700 elements (HTML tags).
</p>
<p><a href="#page-nav">top</a></p>
<h3 id="split">Split Components Across Domains</h3>
<p class="date">tag: content</p>
<p>
    Splitting components allows you to maximize parallel downloads. Make sure you&#8217;re using<br />
    not more than 2-4 domains because of the DNS lookup penalty.<br />
    For example, you can host your HTML and dynamic content<br />
    on <code>www.example.org</code><br />
    and split static components between <code>static1.example.org</code> and <code>static2.example.org</code></p>
<p>
    For more information check<br />
    &#8220;<a href="http://yuiblog.com/blog/2007/04/11/performance-research-part-4/">Maximizing Parallel Downloads in the Carpool Lane</a>&#8221; by Tenni Theurer and Patty Chi.</p>
<p><a href="#page-nav">top</a></p>
<h3 id="iframes">Minimize the Number of iframes</h3>
<p class="date">tag: content</p>
<p>
    Iframes allow an HTML document to be inserted in the parent document.<br />
    It&#8217;s important to understand how iframes work so they can be used effectively.
</p>
<p>
    <code>&lt;iframe&gt;</code> pros:
</p>
<ul>
<li class="bullist">Helps with slow third-party content like badges and ads</li>
<li class="bullist">Security sandbox</li>
<li class="bullist">Download scripts in parallel</li>
</ul>
<p>
    <code>&lt;iframe&gt;</code> cons:
</p>
<ul>
<li class="bullist">Costly even if blank</li>
<li class="bullist">Blocks page onload</li>
<li class="bullist">Non-semantic</li>
</ul>
<p><a href="#page-nav">top</a></p>
<h3 id="no404">No 404s</h3>
<p class="date">tag: content</p>
<p>    HTTP requests are expensive so making an HTTP request and getting a useless response (i.e. 404 Not Found)<br />
    is totally unnecessary and will slow down the user experience without any benefit.
</p>
<p>
    Some sites have helpful 404s &#8220;Did you mean X?&#8221;, which is great for the user<br />
    experience but also wastes server resources (like database, etc).<br />
    Particularly bad is when the link to an external JavaScript is wrong and the result is a 404.<br />
    First, this download will block parallel downloads. Next the browser may try to parse<br />
    the 404 response body as if it were JavaScript code, trying to find something usable in it.
</p>
<p><a href="#page-nav">top</a></p>
<h3 id="cookie_size">Reduce Cookie Size</h3>
<p class="date">tag: cookie</p>
<p>
    HTTP cookies are used for a variety of reasons such as authentication and personalization.<br />
    Information about cookies is exchanged in the HTTP headers between web servers and browsers.<br />
    It&#8217;s important to keep the size of cookies as low as possible to minimize the impact on the user&#8217;s response time.
</p>
<p>
    For more information check<br />
    <a href="http://yuiblog.com/blog/2007/03/01/performance-research-part-3/">&#8220;When the Cookie Crumbles&#8221;</a> by Tenni Theurer and Patty Chi.<br />
    The take-home of this research:
</p>
</p>
<ul>
<li class="bullist">Eliminate unnecessary cookies</li>
<li class="bullist">Keep cookie sizes as low as possible to minimize the impact on the user response time</li>
<li class="bullist">Be mindful of setting cookies at the appropriate domain level so other sub-domains are not affected</li>
<li class="bullist">Set an Expires date appropriately. An earlier Expires date or none removes the cookie sooner, improving the user response time</li>
</ul>
<p><a href="#page-nav">top</a></p>
<h3 id="cookie_free">Use Cookie-free Domains for Components</h3>
<p class="date">tag: cookie</p>
<p>
    When the browser makes a request for a static image and sends cookies together with the request,<br />
    the server doesn&#8217;t have any use for those cookies. So they only create network traffic for no good<br />
    reason. You should make sure static components are requested with cookie-free requests. Create<br />
    a subdomain and host all your static components there.
</p>
<p>
    If your domain is <code>www.example.org</code>, you can host your static components<br />
    on <code>static.example.org</code>. However, if you&#8217;ve already set cookies on the top-level domain<br />
    <code>example.org</code> as opposed to <code>www.example.org</code>, then all the requests to<br />
    <code>static.example.org</code> will include those cookies. In this case, you can buy a whole new domain, host your static<br />
    components there, and keep this domain cookie-free. Yahoo! uses <code>yimg.com</code>, YouTube uses <code>ytimg.com</code>,<br />
    Amazon uses <code>images-amazon.com</code> and so on.</p>
<p>
    Another benefit of hosting static components on a cookie-free domain is that some proxies might refuse to cache<br />
    the components that are requested with cookies.<br />
    On a related note, if you wonder if you should use example.org or www.example.org for your home page, consider the cookie impact.<br />
    Omitting www leaves you no choice but to write cookies to <code>*.example.org</code>, so for performance reasons it&#8217;s best to use the<br />
    www subdomain and<br />
    write the cookies to that subdomain.
</p>
<p><a href="#page-nav">top</a></p>
<h3 id="dom_access">Minimize DOM Access</h3>
<p class="date">tag: javascript</p>
<p>
    Accessing DOM elements with JavaScript is slow so in order to have a more responsive page, you should:
</p>
<ul>
<li class="bullist">Cache references to accessed elements</li>
<li class="bullist">Update nodes &#8220;offline&#8221; and then add them to the tree</li>
<li class="bullist">Avoid fixing layout with JavaScript</li>
</ul>
<p>
    For more information check the YUI theatre&#8217;s<br />
    <a href="http://yuiblog.com/blog/2007/12/20/video-lecomte/">&#8220;High Performance Ajax Applications&#8221;</a></p>
<p>    by Julien Lecomte.
</p>
<p><a href="#page-nav">top</a></p>
<h3 id="events">Develop Smart Event Handlers</h3>
<p class="date">tag: javascript</p>
<p>
    Sometimes pages feel less responsive because of too many event handlers attached to different<br />
    elements of the DOM tree which are then executed too often. That&#8217;s why using <em>event delegation</em> is a good approach.<br />
    If you have 10 buttons inside a <code>div</code>, attach only one event handler to the div wrapper, instead of<br />
    one handler for each button. Events bubble up so you&#8217;ll be able to catch the event and figure out which button it originated from.</p>
<p>
    You also don&#8217;t need to wait for the onload event in order to start doing something with the DOM tree.<br />
    Often all you need is the element you want to access to be available in the tree. You don&#8217;t have to wait for all images to be downloaded.</p>
<p>    <code>DOMContentLoaded</code> is the event you might consider using instead of onload, but until it&#8217;s available in all browsers, you<br />
    can use the <a href="http://developer.yahoo.com/yui/event/">YUI Event</a> utility, which has an <code><a href="http://developer.yahoo.com/yui/event/#onavailable">onAvailable</a></code> method.
</p>
<p>
    For more information check the YUI theatre&#8217;s<br />
    <a href="http://yuiblog.com/blog/2007/12/20/video-lecomte/">&#8220;High Performance Ajax Applications&#8221;</a></p>
<p>    by Julien Lecomte.
</p>
<p><a href="#page-nav">top</a></p>
<h3 id="csslink">Choose &lt;link&gt; over @import</h3>
<p class="date">tag: css</p>
<p>
    One of the previous best practices states that CSS should be at the top in order to allow for<br />
    progressive rendering.
</p>
<p>
    In IE <code>@import</code> behaves the same as using <code>&lt;link&gt;</code> at the bottom of the page, so it&#8217;s best not to use it.
</p>
<p><a href="#page-nav">top</a></p>
<h3 id="no_filters">Avoid Filters</h3>
<p class="date">tag: css</p>
<p>
    The IE-proprietary <code>AlphaImageLoader</code> filter aims to fix a problem with semi-transparent true color PNGs in IE versions &lt; 7.<br />
    The problem with this filter is that it blocks rendering and freezes the browser while the image is being downloaded.<br />
    It also increases memory consumption and is applied per element, not per image, so the problem is multiplied.
</p>
<p>
    The best approach is to avoid <code>AlphaImageLoader</code> completely and use gracefully degrading PNG8 instead, which are fine in IE.<br />
    If you absolutely need <code>AlphaImageLoader</code>, use the underscore hack <code>_filter</code> as to not penalize your IE7+ users.
</p>
<p><a href="#page-nav">top</a></p>
<h3 id="opt_images">Optimize Images</h3>
<p class="date">tag: images</p>
<p>
    After a designer is done with creating the images for your web page, there are still some things you can try before you<br />
    FTP those images to your web server.
</p>
<ul>
<li class="bullist">You can check the GIFs and see if they are using a palette size corresponding<br />
        to the number of colors in the image. Using <a href="http://www.imagemagick.org">imagemagick</a> it&#8217;s easy to check using<br />
        <br />
        <code>identify -verbose image.gif</code></p>
<p>
        When you see an image useing 4 colors and a 256 color &#8220;slots&#8221; in the palette, there is room for improvement.
    </li>
<li class="bullist">
        Try converting GIFs to PNGs and see if there is a saving. More often than not, there is.<br />
        Developers often hesitate to use PNGs due to the limited support in browsers, but this is now a thing of the past.<br />
        The only real problem is alpha-transparency in true color PNGs, but then again, GIFs are not true color and don&#8217;t<br />
        support variable transparency either.<br />
        So anything a GIF can do, a palette PNG (PNG8) can do too (except for animations).<br />
        This simple imagemagick command results in totally safe-to-use<br />
        PNGs:<br />
        <code>convert image.gif image.png</code><br />
        <br />
        &#8220;All we are saying is: Give PiNG a Chance!&#8221;
    </li>
<li class="bullist">
        Run <a href="http://pmt.sourceforge.net/pngcrush/">pngcrush</a> (or any other PNG optimizer tool) on all your PNGs. Example:<br />
        <br />
        <code>pngcrush image.png -rem alla -reduce -brute result.png</code>
    </li>
<li class="bullist">
        Run jpegtran on all your JPEGs. This tool does lossless JPEG operations such as rotation and can also be used to optimize<br />
        and remove comments and other useless information (such as EXIF information) from your images.<br />
        </p>
<p>        <code>jpegtran -copy none -optimize -perfect src.jpg dest.jpg</code>
    </li>
</ul>
<p><a href="#page-nav">top</a></p>
<h3 id="opt_sprites">Optimize CSS Sprites</h3>
<p class="date">tag: images</p>
<ul>
<li class="bullist">Arranging the images in the sprite horizontally as opposed to vertically usually results in a smaller file size.</li>
<li class="bullist">Combining similar colors in a sprite helps you keep the color count low, ideally under 256 colors so to fit in a PNG8.</li>
<li class="bullist">&#8220;Be mobile-friendly&#8221; and don&#8217;t leave big gaps between the images in a sprite. This doesn&#8217;t affect the file size as much<br />
        but requires less memory for the user agent to decompress the image into a pixel map.<br />
        100&#215;100 image is 10 thousand pixels, where 1000&#215;1000 is 1 million pixels
        </li>
</ul>
<p><a href="#page-nav">top</a></p>
<h3 id="no_scale">Don&#8217;t Scale Images in HTML</h3>
<p class="date">tag: images</p>
<p>    Don&#8217;t use a bigger image than you need just because you can set the width and height in HTML.<br />
    If you need <br />
        <code>&lt;img width="100" height="100" src="mycat.jpg" alt="My Cat" /&gt;</code><br />
    <br />
    then your image (mycat.jpg) should be 100&#215;100px rather than a scaled down 500&#215;500px image.</p>
<p><a href="#page-nav">top</a></p>
<h3 id="favicon">Make favicon.ico Small and Cacheable</h3>
<p class="date">tag: images</p>
<p>
    The favicon.ico is an image that stays in the root of your server.<br />
    It&#8217;s a necessary evil because even if you don&#8217;t care about it the<br />
    browser will still request it, so it&#8217;s better not to respond with a <code>404 Not Found</code>.<br />
    Also since it&#8217;s on the same server, cookies are sent every time it&#8217;s requested.<br />
    This image also interferes with the download sequence, for example in IE when you request<br />
    extra components in the onload, the favicon will be downloaded before these extra components.
</p>
<p>    So to mitigate the drawbacks of having a favicon.ico make sure:
</p>
<ul>
<li class="bullist">It&#8217;s small, preferably under 1K.</li>
<li class="bullist">Set Expires header with what you feel comfortable (since you cannot rename it if you decide to change it).<br />
        You can probably safely set the Expires header a few months in the future.<br />
        You can check the last modified date of your current favicon.ico to make an informed decision.
    </li>
</ul>
<p>
    <a href="http://www.imagemagick.org">Imagemagick</a> can help you create small favicons
</p>
<p><a href="#page-nav">top</a></p>
<h3 id="under25">Keep Components under 25K</h3>
<p class="date">tag: mobile</p>
<p>
    This restriction is related to the fact that iPhone won&#8217;t cache components bigger than 25K.<br />
    Note that this is the <em>uncompressed</em> size. This is where minification is important<br />
    because gzip alone may not be sufficient.
</p>
<p>
    For more information check &#8220;<a href="http://yuiblog.com/blog/2008/02/06/iphone-cacheability/">Performance Research, Part 5: iPhone Cacheability &#8211; Making it Stick</a>&#8221; by Wayne Shea and Tenni Theurer.
</p>
<p><a href="#page-nav">top</a></p>
<h3 id="multipart">Pack Components into a Multipart Document</h3>
<p class="date">tag: mobile</p>
<p>    Packing components into a multipart document is like an email with attachments,<br />
    it helps you fetch several components with one HTTP request (remember: HTTP requests are expensive).<br />
    When you use this technique, first check if the user agent supports it (iPhone does not).</p>
<h3 id="emptysrc">Avoid Empty Image src</h3>
<p class="date">tag: server</p>
<p>Image with empty string <b>src</b> attribute occurs more than one will expect. It appears in two form: </p>
<ol>
<li>straight HTML<br />
<blockquote><p>&lt;img src=&#8221;"&gt;</p></blockquote>
</li>
<li>JavaScript<br />
<blockquote><p>var img = new Image();<br />
img.src = &#8220;&#8221;;</p></blockquote>
</li>
</ol>
<p>
Both forms cause the same effect: browser makes another request to your server.</p>
<ul>
<li class="bullist"><b>Internet Explorer</b> makes a request to the directory in which the page is located.</li>
<li class="bullist"><b>Safari and Chrome</b> make a request to the actual page itself.</li>
<li class="bullist"><b>Firefox</b> 3 and earlier versions behave the same as Safari and Chrome, but version 3.5 addressed this issue<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=444931">[bug 444931]</a> and no longer sends a request.</li>
<li class="bullist"><b>Opera</b> does not do anything when an empty image src is encountered.</li>
</ul>
<p></p>
<p>
<b>Why is this behavior bad? </b>
</p>
<ol>
<li>Cripple your servers by sending a large amount of unexpected traffic, especially for pages that get millions of page views per day.</li>
<li>Waste server computing cycles generating a page that will never be viewed.</li>
<li>Possibly corrupt user data. If you are tracking state in the request, either by cookies or in another way, you have the possibility of destroying data. Even though the image request does not return an image, all of the headers are read and accepted by the browser, including all cookies. While the rest of the response is thrown away, the damage may already be done.</li>
</ol>
<p></p>
<p>The root cause of this behavior is the way that URI resolution is performed in browsers.<br />
This behavior is defined in RFC 3986 &#8211; Uniform Resource Identifiers.<br />
When an empty string is encountered as a URI, it is considered a relative URI and is resolved according to the algorithm defined in section 5.2. This specific example, an empty string, is listed in section 5.4. Firefox, Safari, and Chrome are all resolving an empty string correctly per the specification, while Internet Explorer is resolving it incorrectly, apparently in line with an earlier version of the specification, RFC 2396 &#8211; Uniform Resource Identifiers (this was obsoleted by RFC 3986). So technically, the browsers are doing what they are supposed to do to resolve relative URIs. The problem is that in this context, the empty string is clearly unintentional.
</p>
<p>
HTML5 adds to the description of the <img> tag&#8217;s src  attribute to instruct browsers not to make an additional request in section 4.8.2:</p>
<blockquote><p>
    The src attribute must be present, and must contain a valid URL referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted. If the base URI of the element is the same as the document&#8217;s address, then the src attribute&#8217;s value must not be the empty string.
</p></blockquote>
<p>Hopefully, browsers will not have this problem in the future. Unfortunately, there is no such clause for &lt;script src=&#8221;"&gt; and &lt;link href=&#8221;"&gt;. Maybe there is still time to make that adjustment to ensure browsers don&#8217;t accidentally implement this behavior.</p>
<p>
    This rule was inspired by Yahoo!&#8217;s JavaScript guru Nicolas C. Zakas.  For more information check out his article &#8220;<a href="http://www.nczonline.net/blog/2009/11/30/empty-image-src-can-destroy-your-site/">Empty image src can destroy your site</a>&#8220;.
</p>
<p>Source : http://developer.yahoo.com/performance/rules.html</p>
]]></content:encoded>
			<wfw:commentRss>http://witslog.com/wiki/technical/speed-up-a-website/best-practices-for-speeding-up-your-web-site/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>15+ Tips to Speed Up Your Website, and Optimize Your Code!</title>
		<link>http://witslog.com/wiki/technical/speed-up-a-website/15-tips-to-speed-up-your-website-and-optimize-your-code</link>
		<comments>http://witslog.com/wiki/technical/speed-up-a-website/15-tips-to-speed-up-your-website-and-optimize-your-code#comments</comments>
		<pubDate>Sun, 28 Mar 2010 07:06:56 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Speed up a website]]></category>

		<guid isPermaLink="false">http://witslog.com/wiki/?p=118</guid>
		<description><![CDATA[Once you’ve been coding for a while, you begin to take something for granted. You forget just how smart you really are. How many hundreds of keyboard shortcuts have we memorized? How many languages have we learned? How many frameworks? How many hacks? To say...]]></description>
			<content:encoded><![CDATA[<p>Once you’ve been coding for a while, you begin to take something for granted. You forget just how smart you really are. How many hundreds of keyboard shortcuts have we memorized? How many languages have we learned? How many frameworks? How many hacks? To say that web design/development is an extremely tough industry is putting it lightly. Next, add in the fact that much of what you know today will be considered obsolete in a few years.</p>
<p>Today, we’ll be looking at a crop of tips and tricks that will help beginners speed up their development time, and code more efficiently. You’ll see a mix of quick time savings tips, as well as specific coding tricks to increase your web application’s efficiency.</p>
<p><span id="more-2613"> </span></p>
<h3>Compress Your Images Even Further</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/smushIT.png" alt="compress images" /></div>
<p>When using the “Save for Web” tool in Photoshop, we can compress our images in order to lower their respective file sizes. But, did you know that the compression can be taken even further without sacrificing quality? A site named <a href="http://www.smush.it">Smush.It</a> makes the process a cinch.</p>
<h4>How is This Possible?</h4>
<p>The team at Smush.It use a variety of tools.</p>
<ul>
<li>ImageMagick to identify the image type and to convert GIFs to PNG.</li>
<li>pngcrush to strip unneeded chunks from PNGs. We’re currently experimenting with other PNG tools such as pngout, optipng, pngrewrite that will allow for even better png optimization.</li>
<li>jpegtran to strip all meta data from JPEGs (currently disabled) and try progressive JPEGs.</li>
<li>gifsicle to optimize GIF animations by striping repeating pixels in different frames.</li>
</ul>
<p><em>* The list items above were taken from the <a href="http://smushit.com/faq.php">SmushIt FAQ Page </a>.</em></p>
<p>So, just before deploying a new website, run your url through their service to reduce all of your images – thus speeding up your website. <em>Beware – the service may convert your GIF files to PNG. You might need to update your HTML and CSS files accordingly. While we’re on the subject, 99% of the time, saving as a PNG is the better decision. Unless you’re using a tacky animated GIF, consider the PNG format to be best practice. </em></p>
<h3>Be Wise. Use Snippets.</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/dreamweaverSnippets.png" alt="snippets" /></div>
<p>Many IDEs offer a “code snippet” panel that will allow you to save code for later use. Do you find yourself visiting lipsum.com too often to grab the generic text? Why not just save it as a snippet? In Dreamweaver, press “Shift F9? to open the snippet tab. You can then drag the appropriate snippet into the appropriate location. This features saves me SO much time over the course of a week.</p>
<h3>Utilize Console.log() to Debug</h3>
<div class="tutorial_image">
<p><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/consoleLog.png" alt="console.log" /></p>
</div>
<p>You’ve downloaded the jQuery library, and you’re slowly trying to grasp the syntax. Along the way, you hit a snag and realize that you can’t figure out what the value of $someVariable is equal to. Easy, just do…</p>
<div class="dp-highlighter">
<ol class="dp-c">
<li class="alt"><span><span>console.log($someVariable); </span></span></li>
</ol>
</div>
<pre class="js" style="display: none;">console.log($someVariable);</pre>
<p>Now, load up Firefox – make sure you have <a href="https://addons.mozilla.org/firefox/addon/1843">FireBug</a> installed – and press F12. You’ll be presented with the correct value.</p>
<p>Now – multiply this by infinity and take it to the depths of forever and you still won’t realize how useful Firebug and console.log() can be. <img class="wp-smiley" src="http://net.tutsplus.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" /></p>
<h3>Download the Web Developer Toolbar</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/webdevelopertollbar.png" alt="web developer toolbar" /></div>
<p>Created by <a href="http://chrispederick.com/">Chris Pederick</a>, this unbelievably helpful Firefox plugin presents you with a plethora of options. Many of you who watch my screencasts know that I’m a fan of using the “Edit CSS” option to adjust my styles in real-time. Other helpful options include…</p>
<ul>
<li>Easily disable Javascript</li>
<li>Easily disable CSS</li>
<li>Quick HTML/CSS validation links</li>
<li>Rulers</li>
<li>Disable cookies</li>
<li>Too many great features to list!</li>
</ul>
<p><a href="https://addons.mozilla.org/firefox/addon/60">Web Developer Toolbar</a></p>
<h3>Consider Placing Script Tags at the Bottom</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/scriptTagsBottom.png" alt="snippets" /></div>
<p>This is a procedure that we all don’t perform enough. Though not always feasible, you can many times speed up your website by placing your script tags next to the closing &lt;body&gt; tag.</p>
<div class="dp-highlighter">
<div class="bar">
<div class="tools"><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#">view plain</a><a onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;" href="#">copy to clipboard</a><a onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;" href="#">print</a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#">?</a></div>
</div>
<ol class="dp-c">
<li class="alt"><span><span>&#8230;. </span></span></li>
<li><span>&lt;script type=<span class="string">&#8220;text/javascript&#8221;</span><span> src=</span><span class="string">&#8220;someScript.js&#8221;</span><span>&gt;&lt;/script&gt; </span></span></li>
<li class="alt"><span>&lt;script type=<span class="string">&#8220;text/javascript&#8221;</span><span> src=</span><span class="string">&#8220;anotherScript.js&#8221;</span><span>&gt;&lt;/script&gt; </span></span></li>
<li><span>&lt;/body&gt; </span></li>
</ol>
</div>
<pre class="js" style="display: none;">....

&lt;script type="text/javascript" src="someScript.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="anotherScript.js"&gt;&lt;/script&gt;
&lt;/body&gt;</pre>
<h4>Why Does This Help?</h4>
<p>Most current browsers can download a maximum of two components in parallel for each host name. However, when downloading a script, no other downloads can occur. That download must finish before moving forward.</p>
<p>So, when feasible, it makes perfect sense to move these files to the bottom of your document in order to allow the other components (images, css, etc) to load first.</p>
<h3>When Deploying, Compress CSS and Javascript Files</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/javascriptCompress.png" alt="compress files" /></div>
<p>If perfomance is paramount for your website, I strongly suggest that you consider compressing your CSS and Javascript files just before deployment. Don’t bother doing it at the beginning of your development. It’ll only cause more frustration than help. However, once the bow has been tied, compress those babies up.</p>
<h4>Javascript Compression Services</h4>
<ul>
<li><a href="http://javascriptcompressor.com/">Javascript Compressor</a></li>
<li><a href="http://www.xmlforasp.net/JSCompressor.aspx">JS Compressor</a></li>
</ul>
<h4>CSS Compression Services</h4>
<ul>
<li><a href="http://www.cssoptimiser.com/">CSS Optimiser</a></li>
<li><a href="http://www.cssdrive.com/index.php/main/csscompressor/">CSS Compressor</a></li>
<li><a href="http://www.cleancss.com/">Clean CSS</a></li>
</ul>
<p>Two other helpful tools for packing JavaScript code are <a href="http://developer.yahoo.com/yui/compressor/">YUI Compressor</a>, and <a href="http://crockford.com/javascript/jsmin">JSMin</a>.</p>
<p>Additionally, you have the option of compressing your HTML – though I wouldn’t recommend it. The file reduction is negligible.</p>
<h3>jQuery “Quick Tip” Roundup</h3>
<div class="tutorial_image"><img style="width: 300px; display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/jQuery.png" alt="jQuery Tips" /></div>
<p>Not too long ago, Jon Hobbs-Smith from <a href="http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx">tvidesign.co.uk</a> posted a fantastic article that details 25 jQuery tips. Be sure to bookmark this page! Here are several of my favorites.</p>
<h4>Check if an element exists.</h4>
<div class="dp-highlighter">
<div class="bar">
<div class="tools"><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#">view plain</a><a onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;" href="#">copy to clipboard</a><a onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;" href="#">print</a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#">?</a></div>
</div>
<ol class="dp-c">
<li class="alt"><span><span class="keyword">if</span><span> ($(&#8216;#myDiv).length) { </span></span></li>
<li><span> <span class="comment">// this code will only run if the div with an id of #myDiv exists.</span><span> </span></span></li>
<li class="alt"><span>} </span></li>
</ol>
</div>
<pre class="js" style="display: none;">if ($('#myDiv).length) {
  // this code will only run if the div with an id of #myDiv exists.
}</pre>
<h4>Use a Context</h4>
<p>Many people don’t realize that, when accessing dom elements, the jQuery function accepts a second parameter – “context”. Consider the following…</p>
<div class="dp-highlighter">
<div class="bar">
<div class="tools"><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#">view plain</a><a onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;" href="#">copy to clipboard</a><a onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;" href="#">print</a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#">?</a></div>
</div>
<ol class="dp-c">
<li class="alt"><span><span class="keyword">var</span><span> myElement = $(</span><span class="string">&#8216;#someElement&#8217;</span><span>); </span></span></li>
</ol>
</div>
<pre class="js" style="display: none;">var myElement = $('#someElement');</pre>
<p>This code will require jQuery to traverse the entire DOM. We can improve the speed by using a context as the second parameter.</p>
<div class="dp-highlighter">
<div class="bar">
<div class="tools"><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#">view plain</a><a onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;" href="#">copy to clipboard</a><a onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;" href="#">print</a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#">?</a></div>
</div>
<ol class="dp-c">
<li class="alt"><span><span class="keyword">var</span><span> myElement = $(</span><span class="string">&#8216;#someElement&#8217;</span><span>, $(</span><span class="string">&#8216;.someContainer&#8217;</span><span>)); </span></span></li>
</ol>
</div>
<pre class="js" style="display: none;">var myElement = $('#someElement', $('.someContainer'));</pre>
<p>Now we’re telling jQuery to only search within the .someContainer element, and to ignore everything outside of it.</p>
<h4>Use IDs Instead of Classes</h4>
<p>When accessing IDs with jQuery, the library uses the traditional “getElementById” method. However, when accessing classes, jQuery must use its own methods to traverse the dom (there isn’t a native “getElementByClass” method). As a result, it takes a bit longer!</p>
<p><a href="http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx">Review All 25 Tips! </a></p>
<h3>Use $_GET instead of $_POST, if Possible</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/querystrings.png" alt="querystrings" /></p>
</div>
<p>If you have the choice between $_GET or $_POST when making AJAX calls, choose the former.</p>
<blockquote style="background: none repeat scroll 0% 0% #f0f0f0; border: 1px solid #cecfd0; padding: 2em;"><p>“The Yahoo! Mail team found that when using XMLHttpRequest, POST is implemented in the browsers as a two-step process: sending the headers first, then sending data. So it’s best to use GET, which only takes one TCP packet to send (unless you have a lot of cookies).” – Developer.Yahoo.com</p></blockquote>
<p>Remember – don’t blindly use $_GET. Make sure you know exactly what you’re doing first. For example, under no circumstances should you mix the querystring and database access. Not too long ago, one of my <a href="http://www.twitter.com/NETTUTS">Twitter</a> buddies sent me an image of a live website containing a MYSQL query in the url. DON’T DO THIS! <img class="wp-smiley" src="http://net.tutsplus.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" /></p>
<p style="float: left;">
<div class="tutorial_image"><script type="text/javascript">// <![CDATA[
 google_ad_client = "pub-9093712935949486"; /* 468x60 Nettuts Week 3 Middle */ google_ad_slot = "7549675954"; google_ad_width = 468; google_ad_height = 60;
// ]]&gt;</script><br />
<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript">
</script><script src="http://pagead2.googlesyndication.com/pagead/expansion_embed.js"></script><script src="http://googleads.g.doubleclick.net/pagead/test_domain.js"></script><script type="text/javascript">// <![CDATA[
google_protectAndRun("ads_core.google_render_ad", google_handleError, google_render_ad);
// ]]&gt;</script><ins style="display: inline-table; border: medium none; height: 60px; margin: 0pt; padding: 0pt; position: relative; visibility: visible; width: 468px;"><ins style="display: block; border: medium none; height: 60px; margin: 0pt; padding: 0pt; position: relative; visibility: visible; width: 468px;"></ins></ins></div>
<h3>When Practical, Use Libraries and Frameworks</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/frameworks.png" alt="use frameworks" /></div>
<p>Whether you’re using PHP, ASP.NET, Mootools, jQuery – or a combination of all of them, consider using frameworks when appropriate.</p>
<p>For example:</p>
<ul>
<li> if I’m running a simple static website and only need a small bit of Javascript to create a rollover effect, importing the jQuery script will be inappropriate.</li>
<li>If the most complicated feature of my static website is pulling in an XML file, I don’t need to use a framework. In such instances, my site will suffer and cost me more money in extra bandwidth expenditures.</li>
</ul>
<p>However, if I’m building a complicated site that requires a full CMS and complicated data access, I’ll take a look at one of my preferred language’s frameworks.</p>
<p>Remember – make frameworks work for you; not the other way around. Be smart when making these decisions.</p>
<h3>YSlow</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/ySlowWebsite.png" alt="ySlow" /></div>
<p>YSlow is a wonderful service that checks your website to ensure that it’s as efficient as possible. The Yahoo Dev team, not too long ago, created a set of guidelines, or best practices, that should be followed when developing – many of which are detailed in this article, actually.</p>
<p>There’s a great <a href="http://developer.yahoo.net/blog/archives/2007/08/yslow-podcast-screencast.html">YSlow screencast</a> that demonstrates many time saving techiques. I highly recommend that you view it when you have the chance.</p>
<div class="tutorial_image"><img style="width: 600px; display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/yslowDebug.png" alt="ySlow" /></div>
<h3>Keyboard Shortcuts. Learn Them!</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/keyboard.jpg" alt="template" /></div>
<p>Most experienced designers/developers will agree with me; if I had to go up to the toolbar menu every time I wanted to make a change to my site or design, I’d be lost. I’ve been using keyboard shortcuts for so long that I don’t know the correct location anymore for these commands. I just know that “Shift X” opens the correct panel.</p>
<p>At first, it can seem like wasted knowledge. But, I assure you that it isn’t. I recommend that you do a Google search for “X keyboard shortcuts” – where X is equal to your software (i.e. Photoshop). Print the chart out and place it next to your computer. Over the next few weeks, practice touching your mouse as little as possible. This is one thing that separates the pros from the hobbyists.</p>
<h3>Create a “New Website” Template</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/template.png" alt="template" /></div>
<p>Let’s face it; not every website needs to be some huge and complicated application. Sometimes, we simply want to display our portfolio – probably most of the time for some! In these instances, why not create a simple “template” that contains everything you need to get started.</p>
<p>Within my template folder, I have nested “JS” and “CSS” folders.</p>
<ul>
<li>The former contains my <a href="http://net.tutsplus.com/videos/screencasts/5-easy-ways-to-tackle-ie6s-transparency-issues/">“DD_belatedPNG.js”</a> file (adds 24 bit transparency to PNGs in IE6).</li>
<li>The latter simply contains a blank “default.css” file, and my own custom reset file.</li>
</ul>
<p>In addition, I have an “index.html(php)” file that contains a few code snippets that I use on most of my projects. It’s nothing too fancy, but it saves time!</p>
<div class="dp-highlighter">
<div class="bar">
<div class="tools"><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#">view plain</a><a onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;" href="#">copy to clipboard</a><a onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;" href="#">print</a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#">?</a></div>
</div>
<ol class="dp-xml">
<li class="alt"><span><span>&lt;!DOCTYPE html PUBLIC &#8221;-//W3C//DTD XHTML 1.0 Transitional//EN&#8221; &#8221;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&#8221;</span><span class="tag">&gt;</span><span> </span></span></li>
<li><span><span class="tag">&lt;</span><span class="tag-name">html</span><span> </span><span class="attribute">xmlns</span><span>=</span><span class="attribute-value">&#8220;http://www.w3.org/1999/xhtml&#8221;</span><span class="tag">&gt;</span><span> </span></span></li>
<li class="alt"><span><span class="tag">&lt;</span><span class="tag-name">head</span><span class="tag">&gt;</span><span> </span></span></li>
<li><span> </span></li>
<li class="alt"><span><span class="tag">&lt;</span><span class="tag-name">meta</span><span> </span><span class="attribute">http-equiv</span><span>=</span><span class="attribute-value">&#8220;Content-Type&#8221;</span><span> </span><span class="attribute">content</span><span>=</span><span class="attribute-value">&#8220;text/html; charset=utf-8&#8243;</span><span> </span><span class="tag">/&gt;</span><span> </span></span></li>
<li><span><span class="tag">&lt;</span><span class="tag-name">link</span><span> </span><span class="attribute">rel</span><span>=</span><span class="attribute-value">&#8220;stylesheet&#8221;</span><span> </span><span class="attribute">href</span><span>=</span><span class="attribute-value">&#8220;css/reset.css&#8221;</span><span> </span><span class="tag">/&gt;</span><span> </span></span></li>
<li class="alt"><span><span class="tag">&lt;</span><span class="tag-name">link</span><span> </span><span class="attribute">rel</span><span>=</span><span class="attribute-value">&#8220;stylesheet&#8221;</span><span> </span><span class="attribute">href</span><span>=</span><span class="attribute-value">&#8220;css/default.css&#8221;</span><span> </span><span class="tag">/&gt;</span><span> </span></span></li>
<li><span> </span></li>
<li class="alt"><span>&lt;!&#8211;[if lt IE 7]<span class="tag">&gt;</span><span> </span></span></li>
<li><span><span class="tag">&lt;</span><span class="tag-name">script</span><span> </span><span class="attribute">type</span><span>=</span><span class="attribute-value">&#8220;text/javascript&#8221;</span><span> </span><span class="attribute">src</span><span>=</span><span class="attribute-value">&#8220;js/DD_belatedPNG_0.0.7a-min.js&#8221;</span><span class="tag">&gt;</span><span class="tag">&lt;/</span><span class="tag-name">script</span><span class="tag">&gt;</span><span> </span></span></li>
<li class="alt"><span>&lt;![endif]&#8211;<span class="tag">&gt;</span><span> </span></span></li>
<li><span> </span></li>
<li class="alt"><span><span class="tag">&lt;</span><span class="tag-name">script</span><span> </span><span class="attribute">type</span><span>=</span><span class="attribute-value">&#8220;text/javascript&#8221;</span><span> </span><span class="attribute">src</span><span>=</span><span class="attribute-value">&#8220;http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js&#8221;</span><span class="tag">&gt;</span><span class="tag">&lt;/</span><span class="tag-name">script</span><span class="tag">&gt;</span><span> </span></span></li>
<li><span><span class="tag">&lt;</span><span class="tag-name">title</span><span class="tag">&gt;</span><span>Untitled Document</span><span class="tag">&lt;/</span><span class="tag-name">title</span><span class="tag">&gt;</span><span> </span></span></li>
<li class="alt"><span> </span></li>
<li><span><span class="tag">&lt;</span><span class="tag-name">script</span><span> </span><span class="attribute">type</span><span>=</span><span class="attribute-value">&#8220;text/javascript&#8221;</span><span class="tag">&gt;</span><span> </span></span></li>
<li class="alt"><span> $(function() { </span></li>
<li><span> </span></li>
<li class="alt"><span> }); </span></li>
<li><span><span class="tag">&lt;/</span><span class="tag-name">script</span><span class="tag">&gt;</span><span> </span></span></li>
<li class="alt"><span> </span></li>
<li><span><span class="tag">&lt;/</span><span class="tag-name">head</span><span class="tag">&gt;</span><span> </span></span></li>
<li class="alt"><span> </span></li>
<li><span><span class="tag">&lt;</span><span class="tag-name">body</span><span class="tag">&gt;</span><span> </span></span></li>
<li class="alt"><span> </span></li>
<li><span><span class="tag">&lt;</span><span class="tag-name">div</span><span> </span><span class="attribute">id</span><span>=</span><span class="attribute-value">&#8220;container&#8221;</span><span class="tag">&gt;</span><span> </span></span></li>
<li class="alt"><span> </span></li>
<li><span><span class="tag">&lt;/</span><span class="tag-name">div</span><span class="tag">&gt;</span><span class="comments">&lt;!&#8211;end container&#8211;&gt;</span><span> </span></span></li>
<li class="alt"><span> </span></li>
<li><span><span class="tag">&lt;/</span><span class="tag-name">body</span><span class="tag">&gt;</span><span> </span></span></li>
<li class="alt"><span><span class="tag">&lt;/</span><span class="tag-name">html</span><span class="tag">&gt;</span><span> </span></span></li>
</ol>
</div>
<pre class="html" style="display: none;">&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;

&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
&lt;link rel="stylesheet" href="css/reset.css" /&gt;
&lt;link rel="stylesheet" href="css/default.css" /&gt;

&lt;!--[if lt IE 7]&gt;
&lt;script type="text/javascript" src="js/DD_belatedPNG_0.0.7a-min.js"&gt;&lt;/script&gt;

&lt;![endif]--&gt;

&lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"&gt;&lt;/script&gt;
&lt;title&gt;Untitled Document&lt;/title&gt;

&lt;script type="text/javascript"&gt;
	$(function() {

	});
&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;

&lt;div id="container"&gt;

&lt;/div&gt;&lt;!--end container--&gt;

&lt;/body&gt;
&lt;/html&gt;</pre>
<p>As you can see, I reference my CSS and Javascript files, link to Google’s jQuery file, create the document.ready() jQuery function, and open up the standard “container” div.</p>
<p>It’s rather simplistic, but SAVES TIME. So every time you create a new website, simply copy your “template” folder and dig in.</p>
<h3>Inline Vs. External</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/inline.jpg" alt="inline and external" /></div>
<p>Generally speaking, all of your CSS and Javascript should be removed from the page and placed in their own respective external files.</p>
<h4>Why Should We Do This?</h4>
<ul>
<li>Cleaner code.</li>
<li>Separation of presentation and content is crucial.</li>
<li>By using external files, the data will be cached for future use. This reduces the HTML file size without causing an additional HTTP request – because of the caching.</li>
</ul>
<p>If you only have a few basic styles, an exception can be made. In those, and only those instances, it might be beneficial to include them in the HTML page.</p>
<h3>Determine if a PHP Script Was Called With Javascript</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/requestedWith.png" alt="inline and external" /></div>
<p>AJAX is all the rage right now – mostly because it’s finally become relatively user-friendly, thanks to Javascript libraries. In some instances, you need to have a way to determine if the script was called with Javascript. There are a few days to accomplish this task.</p>
<p>One way would be to append a unique key-value pair with Javascript when sending the POST. You could then use PHP to determine if that particular key exists. If it does, we know that Javascript is enabled.</p>
<p>A better way would be to use a built in PHP feature called “HTTP_X_REQUESTED_WITH”. To illustrate…</p>
<div class="dp-highlighter">
<div class="bar">
<div class="tools"><a onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" href="#">view plain</a><a onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;" href="#">copy to clipboard</a><a onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;" href="#">print</a><a onclick="dp.sh.Toolbar.Command('About',this);return false;" href="#">?</a></div>
</div>
<ol class="dp-c">
<li class="alt"><span><span class="keyword">if</span><span> isset(</span><span class="vars">$_SERVER</span><span>[</span><span class="string">'HTTP_X_REQUESTED_WITH'</span><span>]) { </span></span></li>
<li><span> <span class="comment">// write some code and rest assured that the Javascript is enabled.</span><span> </span></span></li>
<li class="alt"><span>} <span class="keyword">else</span><span> { </span></span></li>
<li><span> <span class="comment">// Do something different to compensate for users that have JS turned off.</span><span> </span></span></li>
<li class="alt"><span>} </span></li>
</ol>
</div>
<pre class="php" style="display: none;">if isset($_SERVER['HTTP_X_REQUESTED_WITH']) {
  // write some code and rest assured that the Javascript is enabled.
} else {
  // Do something different to compensate for users that have JS turned off.
}</pre>
<h3>Link to Google’s CDN</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/linkToGoogle.png" alt="link to google" /></div>
<p>Not too long ago, Google began hosting popular scripts such as jQuery. If you’re using such a library, it is strongly recommended that you link to Google’s CDN rather than using your own script.</p>
<p><a href="http://code.google.com/apis/ajaxlibs/">AJAX Libraries API</a></p>
<h4>How Come?</h4>
<ol>
<li><strong>Caching: </strong>There is a possibility that your users won’t need to download the script at all! When a browser sees a request for a file that has already been downloaded onto the user’s computer, it recognizes this and returns a “304? response (NOT MODIFIED). For example, let’s imagine that one user visits thirty sites that all link to Google’s CDN. In this example, the user would only download jQuery once!</li>
<li><strong>Improve Parallelism: </strong> I spoke of this in a previous tip. By removing this extra request, the user’s browser can download more content in parallel.</li>
</ol>
<h3>Embrace Firefox Extensions</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/firefoxExtensions.png" alt="embrace firefox extensions" /></div>
<p>I’m a huge fan of Google’s Chrome. It opens extremely fast and processes Javascript quicker than any other browser – at least for now (I think the latest version of Firefox might have caught up.).</p>
<p>However, you won’t see me leaving Firefox any time soon. The number of helpful plugins available for the browser is astounding. Here’s a list of my favorites.</p>
<ul>
<li><a href="https://addons.mozilla.org/firefox/addon/60"><strong>Web Developer Toolbar</strong></a></li>
<li><a href="https://addons.mozilla.org/en-US/firefox/addon/3247"><strong>S3 Organizer</strong></a></li>
<li><a href="https://addons.mozilla.org/en-US/firefox/addon/1347"><strong>Clippings</strong></a></li>
<li><a href="https://addons.mozilla.org/firefox/addon/1843"><strong>Firebug</strong></a></li>
<li><a href="https://addons.mozilla.org/firefox/addon/1419"><strong>IE Tab</strong></a></li>
<li><a href="http://fireftp.mozdev.org/"><strong>FireFTP</strong></a></li>
<li><a href="https://addons.mozilla.org/en-US/firefox/addon/201"><strong>DownThemAll</strong></a></li>
<li><a href="https://addons.mozilla.org/firefox/addon/5369"><strong>YSlow</strong></a></li>
</ul>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/firefoxEnxtensionZOOMED.png" alt="embrace firefox extensions" /></div>
<h3>When Helpful, Use an IDE</h3>
<div class="tutorial_image"><img style="display: inline;" src="http://nettuts.s3.amazonaws.com/180_efficientcode/ide.png" alt="use an ide" /></div>
<p>In the same way that it’s cool to hate Microsoft right now, it seems that it’s popular at the moment for  people to attack those who use IDEs when developing. This is just silly.</p>
<p>In many instances, the use of an advanced IDE is paramount – especially when working in OOP languages. Now, if you’re simply creating a small HTML template, programs like <a href="http://notepad-plus.sourceforge.net/uk/site.htm">Notepad++</a> and <a href="http://www.panic.com/coda/">Coda</a> will work splendidly. Actually I’d recommend their usage in these instances. Don’t add the extra bloat if you don’t need it. However, when developing advanced applications, take advantage of an IDE.</p>
<h3>That’s All Folks!</h3>
<p>That should do it for now. Hopefully, a few of these (maybe all of them!) will help to make you a better designer and developer. What are some of your favorite short-cuts? Leave a comment below and let us know!</p>
]]></content:encoded>
			<wfw:commentRss>http://witslog.com/wiki/technical/speed-up-a-website/15-tips-to-speed-up-your-website-and-optimize-your-code/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

