Wednesday 19 July 2017

How to speed up your website

Speed Up your Website
Speeding up your website, or in other words “reducing the load time”, is very important as you read in the into.

User experience is much better when a page loads fast.
Search engines like fast loading pages.
With my old website Weethet.nl the load times a very fast. Why?Well … there is absolutely nothing fancy going on there as it was developed back in the year 2000.

My new website, Tweaking4All, is significantly more complex: more JavaScript, more CSS, etc.

Basics First
I will not go too deep in the following basic rules, since most web developers already know these basics. But it’s a good reminder none the less or an easy read for beginners.

The basic steps involve the reduction of your files and file sizes.

Compress JavaScript and CSS files
For CSS and JavaScript you will find quite a few tools out there that can minimize or compact your files.

Optimzing goes (basically) in two steps:

Removing redundant statements, comments or variables.
Removing redunant characters (like spaces, tabs, semi colons, empty lines, etc)
It’s always good to test the result after minimizing a file, since minimizing can cause issues with your JavaScript or CSS files.

Some good sites to do the work for you:

Keep your image files small
Smaller image (and I mean the Kilobytes, not the dimensions) files load faster, so keep them small.

I’ve found that for me it’s always a balance between what works and what doesn’t.

Tip!
Read the following articles to reduce image file sizes even more – both work for the common image formats PNG, JPEG and GIF:

JPEG
JPEG gives a great compression if you tweak it a little bit, specially for photographs.

A downside of JPEG is that JPEG uses a compression method that “takes away” a little of the quality of your image. With photo’s not visible to the eye, but with non-photo’s this can become a problem, specially if the colors need to remain unchanged.

So for example, if I have a picture and a very particular background color (for example to blend in with the background of your website), then it might happen that this background color is no longer exactly the color you wanted it to be. Bummer!

This is basically a consequence of the nature of JPEG – it compresses really well by reducing the quality of an image. In photographs hardly visible, but as you can see below, hard contrasts will cause distortions and/or artifacts might appear (see extreme example below – left is the original, right is the JPEG).

JPEG Artifacts and Distortion
JPEG Artifacts and Distortion

GIF
Well, I would use GIF only if I have no other options (like animation for example), otherwise I’d recommend using PNG.

PNG
PNG is a beautiful format when it comes to lossless compression (no distortion or artifacts) and the use of transparency (for which we used to use GIF). But it comes at a price.

Compression is not always ideal and the files can become pretty big (compared to GIF and JPEG) if you don’t pay attention.

There are quite a few tools out there that scrape of the redundant information of a PNG file, for example ImageOptim.

Note: There is an animation version of PNG, but I consider it useless for now as most browser do not properly support this.

Use fonts instead of images
Back in the day, I used a lot of tiny GIF’s (as individual files or as a sprite where multiple images are combined) to display icons. But these days browsers do support custom fonts that are vector based and are always displayed crystal clear. I use such a font on this website.

A great source for this is the awesome IcoMoon – it does not only offer a truck load of icons, but also a great tool to compile you own font, comes with a web-font generator, and tools to import your own vector drawings. Highly recommended!

Other great source for free web-fonts: Font Squirrel, Google Fonts, Font Awesome and FontStrap.

Use CSS instead of images
CSS has become a very powerful tool over the years. Certain tasks you used to have an image for (for example a gradient) can now be done in CSS – so no more image needed.

Since it’s not always that easy to create the proper CSS code, several so called CSS Generators are out there that help you in creating the right CSS code.

Some great websites to get started:

Reduce file count
For each file that needs to be retrieved, your browser needs to “chat” with your webserver.

A file can be a JavaScript file, a CSS file, a HTML or PHP file, images, etc. The less files a webpage needs, the less overhead the browser has to retrieve those files.

Widely used tricks like merging multiple CSS or JavaScript files into one helps.

The earlier mentioned use of so called “sprites” helps file reduction as well. In CSS Sprites we combine multiple images into a single file and CSS is used to “shift” the visible part of that image.

Some good articles to get started with Sprites: The Mystery of CSS Sprites, W3Schools CSS Sprite Images.

Advanced Speed Techniques
Now that we rehashed the good old basic tricks, on to the more advanced tricks – They are may be more advanced, but most certainly not difficult to implement.

Tip!
For measuring the impact of my changes, I really love to use GTmetrix.It shows me quickly how my page is performing and show where there issue areas are.So before continuing: go over there and get the baseline score …

Please Note ..
Some of these advanced tricks need specific modules to be installed on your web-server.Since I only work with Apache as a webserver, all these examples are Apache based.This does not mean they will not work on your non-Apache webserver, and notation might be slightly different.

To find out what modules are installed on your Apache setup, try this on the command-line (i.e. you need to SSH into your server) – keep in mind that different server can have a different Apache setup:

httpd -M

If that doesn’t work, you could try:

apache2 -M

Compressing Files on the Server
Required module: mod_deflateWhere: .htaccess

Mod_deflate allows us to compress files before sending them to the web-browser.

Compressing files typically has a high impact on text based documents, and guess what: most of your documents are text based (html, css, javascript, xml, html, etc). Files can be reduced to 50% or even less of their original size – and that means: speed!

Oh and by the way: re-compressing images is typically pretty useless.

To enable compression, simply add the following code to your .htaccess file – I placed it as the first thing in my .htaccess file.

The .htaccess file can be found in the root folder of your webpages (typically in the www or public_html folder on a webserver).

1234567891011121314151617181920212223

<IfModule mod_deflate.c># Define compression for certain filetypesAddOutputFilterByType DEFLATE text/plainAddOutputFilterByType DEFLATE text/htmlAddOutputFilterByType DEFLATE text/xmlAddOutputFilterByType DEFLATE text/cssAddOutputFilterByType DEFLATE application/xmlAddOutputFilterByType DEFLATE application/xhtml+xmlAddOutputFilterByType DEFLATE application/rss+xmlAddOutputFilterByType DEFLATE application/javascriptAddOutputFilterByType DEFLATE application/x-javascriptAddOutputFilterByType DEFLATE application/x-httpd-phpAddOutputFilterByType DEFLATE application/x-httpd-fastphpAddOutputFilterByType DEFLATE image/svg+xml
# Drop problematic browsersBrowserMatch ^Mozilla/4 gzip-only-text/htmlBrowserMatch ^Mozilla/4\.0[678] no-gzipBrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html

# Make sure proxies don't deliver the wrong contentHeader append Vary User-Agent env=!dont-vary</IfModule>

Expiration Date – Improve browser caching
Require module: mod_expiresWhere: .htaccess

Your web-browser has a cache, where it stores files for later use so it doesn’t have to download it again. But these files come with an expiration date (time) … and the default times aren’t all that great specially when you, the designer of the website, know that certain files rarely change.

The mod_expires module allows us to define this for particular files. In the example below I set the expiration time to 8 weeks after the initial download of the files. the files in this case are images (.ico, .jpg, .jpeg, .png, .gif), CSS (.css), JavaScript (.js), Flash files (.swf), web-fonts (.woff, .ttf,. eot, .svg) and vector graphics (.svg).

It’s easy to change this to your personal preferences.

Keep in mind (line 8) that the expiration time is expressed as of the time the browser downloaded the file for the first time.

The time can be expressed in:

years
months
weeks
days
hours
minutes
seconds
You can also use the singular expression, for example “month” instead of “months”.

To increase the expiration date, I added the following to my .htaccess file:

1234567

#Expire Header<IfModule mod_expires.c>ExpiresActive On<FilesMatch "\.(ico|jpg|jpeg|png|gif|js|css|swf|woff|ttf|eot|svg)$">ExpiresDefault "access plus 8 weeks"</FilesMatch></IfModule>

CAUTION
Having this option enabled while you are still changing can come with problems – make sure to disable the cache of your web-browser.If that doesn’t work, save the file under a different name after disabling the earlier mentioned code (type a “#” before the lines).

Keep sessions alive
Require module: NoneWhere: httpd.conf

Since a browser needs to reconnect often to retrieve all the files it need, it experiences a lot of overhead.

To minimize this, and the impact is pretty significant (I was baffled by the speed increase!), we can tell Apache to keep the connection alive for a longer time.

Downside to this is that this produces more overhead on your server (memory usage), but with a good setup this should be not a problem if you use the default settings.

There are 2 ways to do these settings:

You webserver management tool (for example CPanel WHM).
Editing the httpd.conf file of your server and restart the httpd service.
Changing the settings in cPanel WHM (Web Host Manager)
Open your cPanel WHM page and go to the “Service Configuration” section and click “Apache Configuration“.

A page opens on the right where you click “Global Configuration“.

When the page reloaded, scroll all the way down and find “Keep-Alive” and modify the settings matching to what you see in the image below:

WHM - Apache Keep Alive settings
WHM – Apache Keep Alive settings

Next click “Save” and WHM will walk you through the process of rebuilding you configuration file and restart Apache.

Manual editing the httpd.conf file
I have not done this myself, since WHM took care of it for me. But I do know that my Apache configuration file is located in “/etc/httpd/conf” and named “httpd.conf“. With you favorite editor, in an SSH session, you’ll need to find and modify the following lines, save the changes and restart Apache:

123

KeepAlive OnKeepAliveTimeout 5MaxKeepAliveRequests 100

Redirecting to another page?
Required Module: NoneWhere: .htaccess

Although redirects are frowned up, sometimes you simply have no choice. For example if a page on your old website no longer exists and needs to point to the correct page on your new website.

I’ve found that plugins, and all kinds of gimmicks do not really work all that great, and all though you should try to avoid them, this is the format I use in my .htaccess file:

Redirect 301 /old/path/to/oldpage.html http://www.newsite.com/new/path/to/newpage.html

This tells the browser that this is a permanent Redirect (301) of the oldpage.html to this newpage.html.

Avoid Redirects when possible …

Complaining about unknown font file types?
Required Module: NoneWhere: .htaccess

I had it with my newly installed web-fonts … the browser kept complaining that it didn’t know what mime type it was. Not a super bad thing, but a minor slowdown and annoying when you keep seeing the messages in your browser console.

A quick fix in .htaccess:

1234

AddType application/vnd.ms-fontobject .eotAddType font/ttf .ttfAddType font/otf .otfAddType application/x-font-woff .woff

Conclusion
With all these tricks I managed to get my “big” and “complex” website to become pretty darn fast (scoring jumped from 65% to a whooping 96% at GTmetrix – which is very good).

I’m pretty sure that there is still room for improvement, but with these few simple steps you will too experience a nice speed boost on your website.
For more….

No comments:

Post a Comment