Thursday, March 24, 2016

Website Performance Optimization

Website performance optimization is always something that should be top priority, especially when there is so much online competition. We don't want to discuss how to optimize and speed up your WordPress, Joomla, Drupal, and more - just use their own websites. But what if you are on custom website design work done? Below are the our optimization tips we recommend, if you are looking to optimize your site.
NYC Moderna Web Design Website Performance Optimization
NYC Moderna Web Design Website Performance Optimization
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 bottle-necking than you can re-adjust your priorities.

Test your Website’s Speed

First we recommend using a website speed test tool to analyze the speed of your website. We suggest using 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.

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.
  • 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.

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 ptimizing, follow these optimization tips below.

Website Performance Optimization Index by ModernaWebDesign.com


  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
 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.

HTTP Request Cleanup

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.


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.


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


  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.



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 a 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) CDN 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 with us (ModernaWebDesign.com) 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.


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:

  1. Cache-control
  2. Pragma
  3. Expires
  4. Validators
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.

Server Cache

There are different forms of server-side caching. This is usually done on higher traffic sites. Server cache is one example which can be very powerful when combined with a caching plugin, and a CDN.

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.

10. HTTP/2 (https:// protocol)

Jeff Atwood, the co-founder of Stack Exchange and Discourse answered 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 a HTTP/2 test tool to see if you are supported. And some CDN providers offer free SSL certificate with their encrypt integration.

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.
Src: 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.

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


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

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]

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.
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

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 a managed host, depending upon your level of expertise and time.

VPS

Our web hosting service is a great cloud VPS provider and you can get started running your website for as little as $9/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.

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 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


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

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 optimizations you can practice to further improve on your performance. 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.

We've written this with love (by ModernaWebDesign.com)

No comments:

Post a Comment