18 Tips for Website Performance Optimization

website performance optimization

Website performance optimization is always something that should be top priority, especially when there is so much online competition. We have written a lot of performance tutorials over the past couple months, such as how to speed up WordPress, Joomla, Drupal, and more. But what if you aren’t on any of those platforms? Below are the top 18 optimization tips we recommend, regardless of the platform, if you are looking to optimize your site.

But before we dive into the tips there are a few tools you should be aware of so that you can first pinpoint your website performance issues. If you know where your website is slowing down or bottlenecking than you can re-adjust your priorities.

Test your Website’s Speed

First we recommend using a website speed test tool to analyze the overall speed of your website. We suggest using KeyCDN’s website speed test tool or WebPageTest as both of these support HTTP/2. Firefox 36+ or Chrome 41+ is required. And you will see more below about why we recommend migrating to HTTPS to take advantage of HTTP/2.

keycdn speed test

Load Test Your Site

Second it is important to load test your site to see what might be causing bottlenecks. Below are few tools which can help test your website. These can also be very useful if you are trying to scale out a platform.

website traffic load test loader

  • Blitz: Performance testing on websites, web apps and REST APIs.
  • Load Impact: Automated and on-demand performance testing for DevOps. Load test your website, web app, mobile app or API instantly with up to 1.2 million concurrent users.
  • WonderNetwork: Easily perform accurate load testing by recording usage with your browser, then playing it back from their servers.
  • Loader: Load testing service that allows you to stress test your web-apps & APIs with thousands of concurrent connections. Free up to 10,000 clients.
  • BlazeMeter: Run massively scalable, open source-based performance tests against all of your apps, and validate performance at every software delivery stage.

If you are running a WordPress site there are also useful plugins such as the WP performance profiler and P3 which can help pinpoint plugins that are slowing down your site.

Calculate Website Performance Optimization Budget

Jonathan Fielding has put together a great free little tool in which you can calculate your performance budget. Simply input how fast in seconds you want your site to load, and pick the connection speed.

website performance optimization budget

On the next page you can adjust the sliders based on the CSS, JS, Images, Video, and font usage on your website.

adjust performance

On the last page it gives you a performance budget breakdown and estimated load times across the board for different connection types. Again these are all estimates but it can be useful to see how much spread there is between all the connection speeds. Don’t forget to optimize for mobile and slower devices.

website performance breakdown

Website Performance Optimization Tips

Now that you have run some tests on your website to see where the delay or load is, it is now time to start optimizing, follow these optimization tips below.

Website Performance Optimization Index

  1. Image Optimization
  2. Reduce HTTP Requests
  3. Minify CSS and Javascript
  4. Critical Path and Render Blocking Resources (CSS + JS)
  5. Reduce Latency with a CDN
  6. Time to First Byte (TTFB)
  7. Avoid 301 Redirects
  8. Caching
  9. Prefetch and Preconnect
  10. HTTP/2
  11. PHP7 and HHVM
  12. Web Font Performance
  13. Hotlink protection
  14. Enable Gzip Compression
  15. Infrastructure
  16. Fix 404 Errors
  17. Serve Scaled Images
  18. Database Optimization

1. Image Optimization

We recently asked 20+ web performance experts to share their advice and mistakes they see people making. And guess what 46% of them said should be the number one focus when it comes to optimization? That’s right, image optimization! So now you’ve heard it from the experts, don’t just take our word for it.

According to a 2016 report from HTTP Archive, on average, 64 percent of a website’s page weight is made up of images. – HTTP Archive

optimus - lossless image compression

KeyCDN developed the Optimus WordPress plugin along with an API which focuses on a combination of both lossless and lossy image compression. If you utilize the API, it can be used with any platform. The PHP library for the Optimus API is available on GitHub. If you are a developer feel free to contribute to the other Optimus API libraries as well.

By using Optimus you can get rid of that Google Pagespeed insight recommendation: By compressing … you could save 4.7 KB (30%) without losses. Another advantage of using Optimus is that it supports conversion to the WebP format which was developed by Google.

According to Google, WebP lossless images are 26% smaller than PNGs and 25-34% smaller than JPEG images.

You can add the following snippet to your .htaccess file to support the serving of WebP format instead of JPEG or PNG images. Note: WebP is currently only supported in Google Chrome and Opera.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_ACCEPT} image/webp
    RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
    RewriteRule ^(path/to/your/images.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]
</IfModule>

<IfModule mod_headers.c>
    Header append Vary Accept env=REDIRECT_accept
</IfModule>

AddType image/webp .webp

And if you are using WordPress you can use KeyCDN’s free WordPress Cache Enabler plugin to serve up the WebP format automatically. Here are some other 3rd party tools you can also utilize for image compression.

Image minify plugins for the automated task systems

3rd Party Online Tools

 Local Tools

Also make sure to take advantage of responsive images using HTML srcset and sizes attributes to serve different scaled images based on the size of the display.

2. Reduce HTTP Requests

When your browser fetches data from a server it does so using HTTP (Hypertext Transfer Protocol). It is a request/response between a client and a host. In general the more HTTP requests your web page makes the slower it will load.

There are many ways you can reduce the number of requests such as:

  • Inline your Javascript (only if it is very small)
  • Using CSS Sprites
  • Reducing assets such as 3rd party plugins that make a large number of external requests
  • Don’t use 3rd party frameworks unless they are absolutely needed
  • Use less code!
  • Combining your CSS and JS files (with HTTP/2 concatenation is no longer as important)

The number of requests a particular website must make varies greatly from site to site. Running a site speed test will tell you how many requests were needed in order to generate a particular page.

reduce http requests

HTTP requests from KeyCDN Speed Test Tool

1st HTTP Request Cleanup Example

Here is an example of a common additional HTTP that can be removed. We have seen a lot of people enable remarketing and advertising in Google Analytics, and yet they don’t actually use this function. Typically users have a tendency to click enable on everything. By enabling this feature you will actually have a 2nd HTTP request for this URL https://stats.g.doubleclick.net/r/collect? which then produces a 302 redirect in your response header.

If you are not using these features you can disable this by turning off “Remarketing” and “Advertising Reporting Features” under “Data Collection” in your Google Analytic’s settings.

google analytics data collection

Or you can manually disable them by adding the following to your Google Analytic’s script.

 ga('set', 'displayFeaturesTask', null);

After disabling this you will no longer have that 2nd HTTP request and your main script will no longer have a 302 redirect. This is just one example of an HTTP request cleanup.

2nd HTTP Request Cleanup Example

Another example of an HTTP request cleanup is if your running WordPress, by default, it includes an additional javascript file wp-emoji-release.min.js?ver=4.3.1 in your header. Emojis are great and all, but are they really needed? It is worth the extra weight and time from the additional JavaScript file? Probably not. You can disable Emojis in WordPress by adding the following code to your your functions.php file.

/**
 * Disable the emoji's
 */
function disable_emojis() {
	remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
	remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
	remove_action( 'wp_print_styles', 'print_emoji_styles' );
	remove_action( 'admin_print_styles', 'print_emoji_styles' );	
	remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
	remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );	
	remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
	add_filter( 'tiny_mce_plugins', 'disable_emojis_tinymce' );
}
add_action( 'init', 'disable_emojis' );

/**
 * Filter function used to remove the tinymce emoji plugin.
 * 
 * @param    array  $plugins  
 * @return   array             Difference betwen the two arrays
 */
function disable_emojis_tinymce( $plugins ) {
	if ( is_array( $plugins ) ) {
		return array_diff( $plugins, array( 'wpemoji' ) );
	} else {
		return array();
	}
}

Or you can also use the free Disable Emojis plugin in the WordPress repository.

Don’t let things generate requests if they aren’t being used! Also don’t just optimize your homepage, the rest of your site deserves attention too.

3. Minify CSS and Javascript

minify css and javascript

Minification of resources means removing unnecessary characters from your HTML, Javascript, and CSS that are not required to load, such as:

  • White space characters
  • New line characters
  • Comments
  • Block delimiters

This speeds up your load times as it reduces the amount of code that has to be requested from the server.

Minify plugins for the automated task systems

JavaScript

CSS

If you are using WordPress you can also minify your CSS and Javascript with WordPress Cache Enabler.

4. Critical Path and Render Blocking Resources (CSS + JS)

chrome devtools render blocking - the DOM

When it comes to analyzing the speed of your web pages you always need to take into consideration what might be blocking the DOM, causing delays in your page load times. These are also referred to as render blocking resources, such as HTML, CSS (this can include web fonts), and Javascript. Here are a few recommendations on how to prevent your CSS and Javascript from blocking the DOM by optimizing your critical rendering path.

CSS

  1. Properly call your CSS files
  2. Use media queries to mark some CSS resources as non-render blocking
  3. Lessen the amount of CSS files (concatenate your CSS files into one file)
  4. Minify Your CSS (remove extra spaces, characters, comments, etc)
  5. Use less CSS overall

Javascript

When it comes to Javascript there are some best practices to always keep in mind.

    1. Move your scripts to the bottom of the page right before your </body> tag.
    2. Use the async or defer directive to avoid render blocking.
    3. Concatenate your JS files into one file (with HTTP/2 this is no longer as important)
    4. Minify your Javascript (remove extra spaces, characters, etc)
    5. Inline your javascript if it is small

Async allows the script to be downloaded in the background without blocking. Then, the moment it finishes downloading, rendering is blocked and that script executes. Render resumes when the script has executed.

<script async src="foobar.js"></script>

Your other option is to defer javascript. This directive does the same thing as async, except it guarantees that scripts execute in the order they were specified on the page. Patrick Sexton has a good example of how to defer loading of javascript properly.

We also discuss your options for  web fonts further down in this post.

5. Reduce Latency with a Content Delivery Network (CDN)

If you are not familiar with a content delivery network (CDN) we highly recommend you read our complete CDN guide. Besides speeding up the delivery of your assets around the globe a CDN also can dramatically decrease your latency.

optimus ping test

50% of your 1-second page load time budget on mobile is taken up by network latency overhead. – WPT

We ran a test to show you the difference in latency times with and without a CDN implemented. This is simply from a connectivity perspective. We used KeyCDN’s ping test tool which conveniently allows us to simultaneously test from the following 10 locations. And here are the results between the two.

Server (POP) Location No CDN RTT (ms) KeyCDN RTT (ms) Difference %
New York, US 36.908 18.096 – 50.97%
Dallas, US 0.751 1.138 + 51.53%
San Francisco, US 39.645 18.900 – 52.33%
Frankfurt, DE 123.072 3.734 – 96.97%
London, UK 127.555 4.548 – 96.43%
Paris, FR 112.417 1.689 – 98.5%
Amsterdam, NL 118.418 10.364 – 91.25%
Singapore, SG 202.682 2.002 – 99.01%
Sydney, AU 191.848 0.705 – 99.63%
Tokyo, JP 130.804 3.379 – 97.42%

The latency between our origin server (without a CDN) and our POPs (with a CDN) on average is decreased by 73%! See the full details of our website latency test.

You can implement a CDN on almost any platform that exists as KeyCDN has over 25 different integrations. Here is a quick list of our integration guides.

6. TTFB

Time to first byte (TTFB) is the measurement of the responsiveness of a web server. Basically it is the time it takes your browser to start receiving information after it has requested it from the server. A website’s TTFB is calculated as:

HTTP request time + Process request time + HTTP response time

TTFB is shown as the green waiting bar in Chrome Dev Tools.

TTFB

By using a CDN, a fast web host, and a reliable DNS provider you can dramatically reduce your overall TTFB. Read more about time to first byte and time to last byte.

7. Avoid 301 Redirects

Redirects are performance killers. Avoid them whenever possible. A redirect will generate additional round trip times (RTT) and therefore quickly doubles the time that is required to load the initial HTML document before the browser even starts to load other assets.

301 redirect

8. Caching

browser server caching

Browser Cache

Leveraging the browser cache is crucial for assets that are rarely changing. It is recommended to have a max-age of 7 days in such cases. There are different types of HTTP headers such as:

  1. Cache-control
  2. Pragma
  3. Expires
  4. Validators

Learn more about different control mechanisms in this article: A Guide to HTTP Cache Headers.

One of the most important HTTP cache headers is probably Cache-Control which is a header comprised of a set of directives that allow you define when / how a response should be cached and for how long. HTTP caching occurs when a browser stores copies of resources for faster access. This can be used with your HTTPS implementation. See our full guide on how to use the cache-control header directives.

If you are using KeyCDN you can add or modify the Expires and Cache-Control response header fields that are sent to the client. This is available within the KeyCDN dashboard under “Zones” → “Edit Zone” →  “Show Advanced Features.”

content delivery network cache-control

  •  -1 Cache-Control: no-cache
  •   0 Push Zone: disabled / Pull Zone: as received from the origin (header honoring)
  • >0 Cache-Control: max-age=t, where t is the time specified in the directive in minutes converted to seconds

This setting overwrites the value received from the origin in case of a pull zone. The expire value only impacts browser cache and not the KeyCDN cache.

Server Cache

There are different forms of server-side caching when it comes to website performance optimization. This is usually done on higher traffic sites. Varnish cache is one example which can be very powerful when combined with a caching plugin, and a CDN. You can also utilize caching plugins which usually exist for each CMS platform.

9. Prefetch and Preconnect

prefetching

Domain name prefetching is a good solution to already resolve domain names before a user actually follows a link. Here an example how to implement it in the HEAD section of your HTML:

<link rel="dns-prefetch" href="//www.example.com">

The double slashes indicate that the URL begins with a host name (this is specified in the RFC1808).

Preconnect allows the browser to set up early connections before an HTTP request is actually sent to the server. Connections such as DNS Lookup, TCP Handshake, and TLS negotiation can be initiated beforehand, eliminating roundtrip latency for those connections and saving time for users.

The example below shows what it looks like to enable preconnect for the zone alias link for KeyCDN.

<link href='https://cdn.keycdn.com' rel='preconnect' crossorigin>

Read our in-depth article on preconnect.

10. HTTP/2

Jeff Atwood, the co-founder of Stack Exchange and Discourse answered in our web perf questions that the number one piece of advice he would give is “HTTP/2 adoption across the board — huge improvements for everyone.” We love Jeff’s answer as we definitely agree that HTTP/2 is the future and there are huge performance benefits.

Go, the programming language, has a great example of when you are dealing with a lot more images on a page and how HTTP/2 far exceeds that of HTTP/1.

To enable HTTP/2 all that is required is an SSL certificate (it requires TLS) and a server that supports HTTP/2. You can use KeyCDN’s HTTP/2 test tool to see if you are supported. And KeyCDN now offer’s free SSL certificates with our Let’s Encrypt integration. Haven’t migrated to HTTPS yet? We have also have an HTTP to HTTPS migration guide.

11. PHP7 and HHVM

Keeping the various components of a web server up to date is critical for reasons such as security patches, performance upgrades, and so on. If you are using PHP, upgrading to PHP7 can help greatly improve performance as compared to PHP 5.6. As well as taking advantage of HHVM.

php7

Source: zend.com

Based on the results from the above image, PHP7 is able to handle 204 requests per seconds compared to PHP 5.6’s 96 in WordPress 3.6 Additionally, PHP7 is able to handle 183 more requests than PHP5.6 in WordPress 4.1.

HHVM, an open-source VM used by websites like Facebook also been shown to produce good results. When testing PHP 7 and HHVM Kinsta got slightly different results from Zend. From their conclusions HHVM wins hands down.

hhvm

A lot of these test results will vary due to environments, hardware, CMS platforms tested, versions, etc. But either way, both PHP7 and HHVM can be great ways to improve the performance of your website.

12. Web Font Performance

top 10 google fonts

According to the HTTP Archive, 60% of websites are now using custom fonts. Which is over an 850% increase since 2011. The disadvantages of web fonts, such as Google Fonts, are that they add extra HTTP requests to external resources. Web fonts are also render blocking. Below are some recommendations for better web font performance.

  1. Prioritize based on browser support
  2. Choose only the styles you need
  3. Keep character sets down to a minimum
  4. Host fonts locally or prefetch
  5. Store in LocalStorage with Base64 Encoding

You can see an example of each method above in our post on analyzing web font performance. Adam Morse, a designer, wrote a great post on how system fonts can be beautiful too and that web fonts are not a requirement for great typography. Georgia is a great system font that comes to mind that looks great and makes for easy readability.

You can also move your Google Fonts to your CDN. We ran our own comparison between using Google’s CDN and KeyCDN, and it was faster to use KeyCDN. Why? Because it reduces the number of HTTP requests, DNS lookups, lets you take advantage of a single HTTP/2 connection, and have more control over caching.

SPEED TEST Google CDN (MS) KEYCDN (MS) WINNER
WebPageTest Load Time 1871ms 1815ms KeyCDN
WebPageTest Fully Loaded 1929ms 1862ms KeyCDN
Pingdom Load Time 355ms 324ms KeyCDN

13. Hotlink Protection

Hotlink protection refers to restricting HTTP referrers in order to prevent others from embedding your assets on other websites. Hotlink protection will save you bandwidth by prohibiting other sites from displaying your images.

Example: Your site URL is www.domain.com. To stop hotlinking of your images from other sites and display a replacement image called donotsteal.jpg from an image host, place this code in your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?domain\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpe?g|gif|bmp|png)$ http://i.imgur.com/donotsteal.gif [L]

KeyCDN also has an easy way to enable hotlink protection to protect your CDN bandwidth. See our tutorial on how to create a zonereferrer.

14. Enable Gzip Compression

Gzip is another form of compression which compresses web pages, CSS, and javascript at the server level before sending them over to the browser. You can check if your site is already compressed by using Check GZIP Compression. This website performance optimization is easy to implement and can make a big difference.

GZIP compression saves 50% to 80% bandwidth and will therefore significantly increase the website’s loading speed. –Check GZIP compression

Apache

You can enable compression by adding the following to your .htaccess file.

<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml

  # Remove browser bugs (only needed for really old browsers)
  BrowserMatch ^Mozilla/4 gzip-only-text/html
  BrowserMatch ^Mozilla/4\.0[678] no-gzip
  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
  Header append Vary User-Agent
</IfModule>

Nginx

You can enable compression by adding the following to your nginx.conf file.

gzip on;
gzip_comp_level 2;
gzip_http_version 1.0;
gzip_proxied any;
gzip_min_length 1100;
gzip_buffers 16 8k;
gzip_types text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
gzip_disable "MSIE [1-6].(?!.*SV1)";
gzip_vary on;

15. Infrastructure

website performance optimization - web hosting

Having a fast web host is equally as important as any website performance optimization you could make, as it is the backbone of your site. Stay away from cheap shared hosting. We suggest going with a VPS or if you are running WordPress or Drupal, a managed host, depending upon your level of expertise and time.

VPS

Digital Ocean is a great cloud VPS provider and you can get started running your website for as little as $5/month. They feature SSDs, 1Gbps network, a dedicated IP address, and you can easily scale up or down in a matter of seconds.

Linode is also another good choice if you are looking for a cloud VPS. They have plans starting at $10/month and all feature SSDs, API, CLI, and easy scaling across 8 datacenters in 3 different regions.

Vultr is slightly newer to the VPS game, but they provide very fast and stable servers throughout their 14 different locations. A newer feature they now offer is DDoS mitigation service.

Managed Hosting

For those less tech savvy a managed host might be a better solution. Yes, you will pay more, but depending on the size of your business and how important your time is, the price sometimes outweighs the cost.

Here are some popular managed WordPress hosts that focus on high-performance:

Here are some popular managed Drupal hosts:

16. Fix 404 Errors

Any missing file generates a 404 HTTP error. Depending upon the platform you are running 404 errors can be quite taxing on your server. For example, Drupal has very expensive 404 errors. On an ‘average’ site with an ‘average’ module load, you can be looking at 60-100MB of memory being consumed on your server to deliver a 404.

We don’t recommend installing plugins or modules to check for 404s, instead we advise you occasionally run your website through an external service such as the “Online Broken Link Checker” or a tool like Screaming Frog. This ensures that you aren’t wasting any of your server’s resources on this task. You can also see these in Google Search Console.

17. Serve Scaled Images

pagespeed insights

You should always upload your images at scale and not rely on CSS to size them down. If you do you will run into this little Google Pagespeed recommendation: “Optimization suggestion: “By compressing and adjusting the size of … you can save 5.8 KB (51%).

This recommendation refers to your images being scaled down by your browser. For example, maybe the image you upload has a 400px width, but the column it was placed in is only 300px wide. This results in your image being scaled down to 300px due to CSS so that it matches the column size. It is better to always upload images at scale and also upload multiple resolutions of your images and serve the right resolution for the right device.

Note: It is not always possible to avoid scaling with CSS, especially if you are working with high resolution retina devices.

18. Database Optimization

database optimization

And last but not least is database optimization. Whether it is cleaning out old unused tables or creating indexes for faster access there are always things that can be optimized.

MySQL Tuning

Optimizing MySQL is also very important. Unfortunately this is very specific to your environment and your setup so we can’t provide recommended configurations. The MySQL/MariaDB configuration file is normally located in /etc/my.cnf. Here are a few settings though to keep an eye on.

  • tmp_table_size
  • query_cache_type
  • query_cache_size
  • query_cache_size
  • join_buffer_size
  • max_heap_table_size

A highly recommended tool is the MySQL Tuner script. It is read-only and won’t make configuration changes. It will give you an overview of your server’s performance and make some basic recommendations about improvements that you can make after it completes. Here are a couple other tools you can use as well:

Summary

As you can see there are hundreds of different website performance optimization tweaks you can implement to further improve on the delivery and speed of your content. From image optimization, to implementing a CDN, to browser and server caching, taking advantage of HTTP/2, Gzip, PHP7, HHVM, and much more!

Are there some website performance optimization tips that we left out? If so feel free to let us know below or bring up the topic in our community.

Related Articles

18 Tips for Website Performance Optimization was last modified: April 10th, 2017 by Brian Jackson