18 Tips for 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 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. You will see more below about why we recommend migrating to HTTPS to take advantage of HTTP/2.
Load test your website
Second, it is important to load test your website 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.
- CyberFlood: Security and performance testing on websites and applications.
- 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.
- 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 is a useful plugin, such as 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.
On the next page you can adjust the sliders based on the CSS, JS, Images, Video, and font usage on your website.
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 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.
1. Image optimization
We 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 2022 report from HTTP Archive, on average, 45 percent of a website's page weight is made up of images.
- HTTP Archive
KeyCDN developed the Optimus WordPress plugin, which focuses on a combination of both lossless and lossy image compression.
By using Optimus you can get rid of that Google PageSpeed Insights 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.
<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 third party tools you can also utilize for image compression.
Image minify plugins for the automated task systems
- Grunt: grunt-contrib-imagemin
- Gulp: gulp-imagemin
Third 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 third party plugins that make a large number of external requests
- Don't use third 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.
First 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 second 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 Analytics settings.
Or you can manually disable them by adding the following to your Google Analytics 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.
Second 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.
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
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
- Grunt: grunt-contrib-uglify
- Gulp: gulp-uglify
CSS
- Grunt: grunt-contrib-cssmin
- Gulp: gulp-minify-css
If you are using WordPress you can also minify your CSS and JavaScript with the Cache Enabler plugin.
4. Critical path and render blocking resources (CSS + JS)
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
- Properly call your CSS files.
- Use media queries to mark some CSS resources as non-render blocking.
- Lessen the amount of CSS files (concatenate your CSS files into one file).
- Minify Your CSS (remove extra spaces, characters, comments, etc.).
- Use less CSS overall.
JavaScript
When it comes to JavaScript there are some best practices to always keep in mind.
- Move your scripts to the bottom of the page right before your
</body>
tag. - Use the async or defer directive to avoid render blocking.
- Concatenate your JS files into one file (with HTTP/2 this is no longer as important).
- Minify your JavaScript (remove extra spaces, characters, etc.).
- 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.
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 multiple 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 | .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 83%! 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.
- WordPress integration
- CMS integration guides
- Framework integration guides
- AWS S3 CDN integration
- Google Cloud Storage CDN integration
- Custom CDN integration
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 DevTools.
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.
8. 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:
Cache-Control
Pragma
Expires
Learn more about different control mechanisms in our A Guide to HTTP Cache Headers article.
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 and 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. The Expires setting is available within the KeyCDN dashboard by going to the Zone settings.
- -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.
- See our WordPress caching guide
- See our Drupal caching guide
- See our Magento caching guide
- See our XenForo caching guide
9. Prefetch and preconnect
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.
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.
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.
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
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.
- Prioritize based on browser support
- Choose only the styles you need
- Keep character sets down to a minimum
- Host fonts locally or prefetch
- Store in LocalStorage with Base64 Encoding
You can see an example of each method above in our post on analyzing web font performance. 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 | 1871 ms | 1815 ms | KeyCDN |
WebPageTest Fully Loaded | 1929 ms | 1862 ms | KeyCDN |
Pingdom Load Time | 355 ms | 324 ms | 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)$ https://imgur.com/donotsteal [L]
KeyCDN also has an easy way to enable hotlink protection to protect your CDN bandwidth. See our tutorial on how to create a Zone Referrer.
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. This website performance optimization is easy to implement and can make a big difference.
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
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
DigitalOcean 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 11 datacenters.
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-100 MB of memory being consumed on your server to deliver a 404
.
We don't recommend installing plugins or modules to check for 404
errors, 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
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.
It is not always possible to avoid scaling with CSS, especially if you are working with high resolution retina devices.
18. 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:
- MySQL tuning primer script
- phpMyAdmin
- See our WordPress database optimizations
- See our Joomla database optimizations
- See our Magento database optimizations
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.