Performance – How to Optimize WordPress

Making sure that your visitors can view your site as fast as possible is of vital importance to any website. It not only affects the average time a user stays on your site and their return rate, but also your site’s perceived credibility. All of these factors influence the revenue your site can generate. A fast site not only gives a better user experience, but also appears more professional and of a higher quality. Page respond time and load time are also two of the quality factors that influence your Google search ranking.

Analyzing Site Performance

Before you start to optimize your site, you need a way to measure your site’s current performance so that you can quantify any improvements. A convenient way to get this information is to run your site through Pingdom’s Full page test. This tool does a quick visual benchmark of the load time of all components on your site. It gives you a grasp of which components you may need to optimize. Be sure to save the information for later reference.

Pingdom example
An example of a Pingdom benchmark.

Note that in terms of user experience reducing the page load time should not be your main concern. Of greater importance is the time it takes until the visitor is able to access and interact with the page.

A less graphical but more detailed report on your site performance can be obtained using the Web Page Analyzer. This is an excellent tool that analyzes a webpage and gives recommendations for decreasing its load time.

YSlow

The following two Firefox plug-ins will be of immense help as you optimize your site.

Firebug – Provides debugging abilities for Firefox.
YSlow – Integrates with Firebug to add performance analyzing functionality.

With these plug-ins installed, navigate to the page you want to analyze. Next, click on the YSlow icon on the status bar to bring up the YSlow tab of the Firebug window.

YSlow start screen
YSlow start screen.

From there, click the Run Test button to make an instant performance analysis of your website. This will show you where your site is slow and what you can do to improve it.

Look through all of the performance categories, even the ones you already have an “A” grade in, to learn in what areas you may be able to optimize. For each category there is a link to Yahoo’s Performance Rules that further describes how you may implement the optimizations.

YSlow will give your site an overall performance score from 0-100. It is recommended that you bring your site up to at least 80.

YSlow grade tab
YSlow grade tab.

YSlow includes three more tabs – components, statistics and tools – that you should examine as well. In particular, the statistics tab can provide some useful data.

YSlow statistics tab
YSlow statistics tab.

For more information about YSlow, take a look at the YSlow user guide. Another Firebug extension similar to YSlow is Google’s Page Speed plug-in. It will give you Google’s perspective on what makes a high performance website and is definitely worth testing out.

Page Speed – Adds performance analyzing functionality to Firebug, similar to YSlow.

Page Size

Reducing the size of the XHTML document that makes up a web page can significantly improve a page’s load time. As seen in your Pingdom benchmark, the XHTML document needs to be fully downloaded before the browser can start downloading the other components.

A good guideline is that the page size, excluding the components, should not be more than 50kb if possible. To reduce the size of all your pages, you can try to shave off redundant HTML elements from within your CMS template code. You may also want to split content across multiple pages for very large documents.

W3 Total Cache

One of the best techniques for speeding up a WordPress site is to install the W3 Total Cache plug-in. While there is a great number of plug-ins related to WordPress performance, this is the only one you really need. It includes page caching, database caching, minification, http compression and transparent CDN integration, each of which will be explained later in this chapter.

W3 Total Cache – This WP plug-in improves overall site performance.

With this plug-in fully configured and running, there are few remaining optimizations you need to make for your site. Techniques such as reducing the total number of database queries and executed PHP code become unnecessary when you are providing static cached pages to the visitors.

Page Caching

Most CMS – including WordPress – run on PHP, which is an interpreted programming language. This means that any time a visitor arrives at such a site the server has to compile the requested PHP files, execute database queries and finally send the compiled HTML file to the end user. Because of this, commonly mentioned optimization techniques for WordPress sites include:

  • Replacing PHP code with static HTML.
  • Reducing the number of database queries.
  • Removing or disabling plug-ins.

While such changes can significantly improve performance on an uncached WordPress site, they have no effect on a site cached with, for example, W3 Total Cache. On such a site visitors will instead be served precompiled cached HTML files. It is in fact preferable to keep your WordPress template files dynamic with PHP and database queries, in order to make the site easier to modify. You then get the best of both worlds – the speed of static HTML files and the modifiability of dynamic PHP.

Content Delivery Network

A Content Delivery Network or CDN allows you to host your static files on a sub domain which is linked to a wide network of servers all over the world. This means that your static content – such as HTML, cached PHP, images, JavaScript and CSS – is pushed to a server that is closer to the intended recipient, making it load much faster. This will greatly reduce bandwidth consumption and the number of HTTP requests issued to your web server, although at a financial cost.

CDN service providers include, for example, Amazon Cloudfront, Akamai Technologies, Mirror Image Internet and Limelight Networks. Their services are not free, but as your number of visitors grow larger, a CDN becomes necessary to achieve fast response times.

Cache-Control Header

A cache-control header tells the browser how long it should keep content in its cache. This can be used to reduce the page load time and number of HTTP requests for second time visitors. In particular, you want to cache static components that you are unlikely to change – not only images, but also JavaScript files, CSS files and Flash components.

This optimization is performed automatically by W3 Total Cache and it can be configured under the Browser Cache Settings page. Keep in mind that if you use a far future expiration date you normally have to change the component’s filename whenever it is modified in order to ensure consistency across all visitors. However, with W3 Total Cache installed this will be done automatically for you whenever you update a cached component.

Compressing Components

Enabling gzip compression is a simple and effective way to save bandwidth and speed up your site. W3 Total Cache will enable gzip for text-based components automatically. Most images, music and videos should not be gzipped, because they are already compressed. Only text is worth compressing – with CSS, JavaScript and HTML being the most important text files. Only browsers supporting compression will be sent compressed components, making this technique compatible with older browsers.

The tradeoff with gzipping components is an increased server CPU-load. Usually, this is a good tradeoff, given the speed of compression. It is also possible to store gzipped static components and to send over the pre-compressed versions. This is done by default by W3 Total Cache for cached text-based files.

Minimize HTTP Requests

One of the largest factors influencing the page load time is the number of components that are present on that page. Components include everything that requires an extra HTTP request, after the page has been fetched when the visitor’s cache is empty.

Some example components are: images, videos, style sheets, scripts and Flash. There is an inherent overhead in each HTTP request. Therefore, reducing the number of separate components required to render a page will improve its performance for first time visitors.

Split Components across Domains

In order to maximize the number of active download threads, the components can be split across multiple domains. However, because there is a penalty for the DNS to map an IP address from a given hostname, using a separate domain for every component is not a good idea either. It is recommended to use at least two but no more than four domains for optimal performance. This gives a good compromise between reducing DNS lookups and increasing the number of parallel downloads.

Preload Components

By preloading components you can take advantage of the time the browser is idle and request components that the visitor is likely to need in the future. This way, when the user visits the next page, you could have most of the components already in the cache and thereby allow the page to load much faster.

Preloading components typically involves writing JavaScript code that executes after the onload event. An example of such script prefetching that works across many browsers can be found on phpied.com.

Another way of preloading components is by using the HTML <link> tag. This tag, when added to a page, provides a set of prefetching hints to the browser. After the browser is finished loading the page and is idle, it will begin silently prefetching the specified documents and storing them in its cache. This link prefetching is currently only supported by Firefox. However, since Firefox is the second most popular web browser, you can noticeably decrease load times for a large percentage of your visitors just by adding one line of code to your HTML markup. For prefetching purposes, the Firefox browser looks for an HTML <link> tag with a relation type of either “next” or “prefetch”. An example of using the <link> tag to prefetch a web page would look like this:

<link rel="next" href="nextpage.php" />

Link prefetching can also be used for static components, such as images.

<link rel="prefetch" href="image.jpg" />

WordPress sites include a link tag by default to prefetch the next post.

Post-Load Components

The onload event can, in addition to preloading, also be used to post-load components, although this is less common. For example, large images below the fold can be loaded after the rest of the components have finished loading. This can be achieved by using the YUI Image Loader utility, which is part of the YUI JavaScript library. Similarly, there is the YUI Get Utility, which lets you include JS and CSS after the page has loaded.

When the browser makes a request for a static component on a domain that uses cookies, the server will send those cookies along with the request. This creates needless network traffic. Therefore, static components should be hosted on a domain or subdomain different from your website’s domain. This can be achieved, for example, by using a CDN.

CSS and JavaScript

CSS Sprites

CSS sprites are the preferred method for reducing the number of HTTP requests for images. A sprite is an image made up of several smaller images. Using the CSS background-image and background-position properties, you can display the desired image segment from this sprite. For more information you can read about CSS sprites on CSS-Tricks.com.

Make JavaScript and CSS External and Single File

Using external code files generally produces faster pages than inlining the code on the web page, although they require separate HTTP requests. This is because external code files – such as JavaScript and CSS files – are cached by the browser. Therefore, the size of the HTML document is reduced without increasing the number of HTTP requests for second time visitors.

In order to minimize the number of HTTP requests, make sure to put your JavaScript into a single file. Likewise, be sure to place all CSS rules in a single style sheet document. The exception to this is when you have a page that only has one page view per session. In this case, you may find that inlining the code will result in faster load times.

CSS on Top

Placing your site’s style sheet within the <head> element of the document makes pages appear to load faster. This is because it allows the browser to render the page progressively. The browser will display whatever content it has as soon as it can, which gives the visitor visual feedback and improves the overall user experience.

JavaScript on Bottom

JavaScript files should be placed on the bottom of the page whenever possible. This is because scripts block parallel downloads for all but the latest browsers: IE8+, Firefox 3.5+, Chrome 2+ and Safari 4+. In some situations, it is not easy to move scripts to the bottom. For example, if the script uses document.write to insert part of the page’s content, it cannot be moved lower on the page.

Minify JavaScript and CSS

Minification is the practice of removing unnecessary characters from code to reduce its size. When code is minified, all whitespace characters are removed and the code is optimized and restructured so as to load faster. To compress CSS, you can use an online tool, such as CleanCSS. Compressing JavaScript can be done with, for example, the JavaScript Compressor. Note that W3 Total Cache will do these optimizations for you, so if you have that plug-in installed you do not need to manually minify your code.

One optimization that minification tools are unable to do is to find and remove unused CSS rules. A useful Firefox plug-in that can help you perform this task is Dust-Me Selectors. This plug-in can both test pages individually and scan through an entire site in search of unused selectors.

Dust-Me Selectors – A Firefox plug-in that finds unused CSS selectors.

Reducing Download Iterations

When a visitor arrives at your site, their browser will first download the initial HTML web page. Once that page has been received any external components referenced from that page will begin downloading, such as JavaScript and CSS files. If these components in turn contain external components these will have to be downloaded in a third iteration since the browser will not know about them until the first external component has been loaded. This can be seen in the following Pingdom benchmark.

Pingdom three iterations
A page requiring three download iterations.

By removing the third download iteration, the first page view will load faster. Embedding all JavaScript in a single script file, and all CSS rules in a single style sheet file, will remove some of the need for the third download iteration. What you must also do is to begin downloading any images used in the CSS file as soon as the web page has loaded. This is done by referencing the images from an internal style sheet on the web page using the CSS background property. The example below shows a CSS rule that references two images to be prefetched.

<style type="text/css">
#preload {
  background:url( img1.png ) no-repeat -9999px -9999px;
  background:url( img2.png ) no-repeat -9999px -9999px;
}
</style>

Web browsers will not begin fetching a CSS background image until they know for sure that it will be used. Therefore, you need to actually use the CSS rule in the document for this optimization to work. This is the reason why the prefetched images are hidden from view by being moved off the screen. In the code above, the id selector is used, so by applying that selector to the body tag, the images will be prefetched.

<body id="preload">

With this optimization in place, the page previously benchmarked will be able to load in only two download iterations.

Pingdom two iterations
Same page as before, but now requiring only two download iterations.

Image Optimization

Graphics and photos often constitute a significant amount of the page size, so optimizing them should be a high priority. The three image formats supported by all browsers are jpg, gif and png. These formats have the following properties:

PNGJPGGIF
CompressionLossless zip compressionLossy compression, Adjustable quality/sizeLossless compression
TransparencyVariable transparencyNo transparencySingle level transparency
ColorsVariable bit depth
8, 24 or 48 bits
Always 24 bitUp to 256 colors only
Progressive displayTwo-dimensional interlacingProgressive displayOne-dimensional interlacing

For photographic images (continuous tones), the jpg format produces the smallest file size. When saving the file, you can also reduce the size further by selecting a lower quality. For graphics (solid color images), the png format gives file sizes smaller than jpg and in most cases smaller than gif. Basically, png is an excellent substitute for gif that was built to handle the same types of graphics better and faster.

Another important aspect to image optimization is the image dimensions. Typically, you should not scale the width and height of an image down in HTML. This makes the image appear jagged and gives an unnecessarily large download size for the end user. However, it is recommended to include the width and height attributes of the <img> element, in order to state the image’s actual dimensions. This allows the browser to reserve space for the image and to render it faster once it has finished downloading.

To make an image appear to load faster, it can be saved as either “interlaced” (gif/png) or with “progressive loading” (jpg) format. Browsers will then start to draw the image before it is fully loaded. This improves the user experience at the cost of a slightly larger file size. It is most useful for large images that appear above the fold.

A final optimizing technique is to remove unnecessary bytes without changing the visual quality of the image. A useful online tool for this purpose is Smushit.

Compare Results

Are you satisfied with your optimizations? Then it is time to test your site. See if it can outperform your competitors’ sites with Pingdom. You can also sign up for a free account with Pingdom to be able to monitor the page response time from various locations around the world.

This book covers website optimization in depth:
O'Reilly - Even Faster Web Sites