Friday, July 20, 2012

Web Front End Optimization a detailed HOW TO (tutorial)

Table of content:


Requirements

1: Gathering required tools

2: Analyze Your Page Speed

3: Page Speed interface tutorial

4: Front End optimization rules also known as Page Load Speed Optimization

5: Explanations

6: Additional Suggestions


REQUIREMENTS:


Broswers: Google Chrome / Mozilla Firefox
Tools:
Chrome -> Google's Page Speed
Firefox -> Firebug + YSlow / Google's Page Speed

I am not a Firefox fun, but Chrome's one and so we will use Chrome in out examples :)
Hope you are familiar with chrome's magic key "F12"=)

1: Gathering required tools
1.1 : Download Google's Chrome at http://Google.com/Chrome/
1.2 : Install Google's Page Speed Insights from Chrome Store

2: Analyze Your Page Speed
2.1 : Load your page in Chrome (ex. http://google.com)
2.2 : When loaded, press "F12" magic key :)
2.3 : Now you see the tab called "Page Speed", the tab is placed after tab "Console", follow to this tab.
2.4 : Press the "Analyze" button at right top corner to Analyze Page Speed
2.5 : Well Done, page speed is determined. Let's explain what is what.

3: Page Speed interface tutorial
3.1 : Top tab containing two buttons, "Refresh" and "Clear".
3.1.1 : "Refresh" button allows you to re-Analyze page speed
3.1.2 : "Clear" button allows you to clear entire results

3.2 : Left part of window is an overview of Rules that done/undone with it's priority (low/medium/high and experimental)
Follow each one to see what they are asking to do to complete the goal, you can click on every rule for basic explanation or "Learn more" inside the rule, to go to detailed explanation in case you don't understand something.

4: Front End optimization rules also known as Page Load Speed Optimization
4.1 : Clean code
4.2 : Optimize download and content (any content included in page, such as css,js,images,etc)
Page speed optimization : Clean the code
Cleaning you code is very basic rule of Front End Optimization, clean code also looks professional and readable.
Take all inline CSS to you external css file, if you don't have one - create it, preferably under directory called "css","styles", or something suggesting that css files located inside.
On you page should be only ids and classes used and not inline css, see next example.


some content
#id_you_want { display:block;position:relative;height:125px;width:250px; margin-left:20px; }
some content

Look much better. So now follow all your document and move the styles into css files.
How to decide which one to use the (#) id or the (.) class. ID as rule says, can appear only once at page and javascript lookups by ID is faster than by class.
Class can appear as much time as you wish on page. Class is reusable.

Next step is cleaning inline JavaScripts.
Also take all you inline script like:

Move the script's inner content to separate file for further in page inclusion.
For example, you can create scripts.js file and store there all the common scripting pieces and another one called libs.js or libraries.js to store libraries used on all/most of pages.

TableLess HTML
Why using table less HTML ?
The answer is very simple, it is common for modern pages, easy and light weight. In total when you understand good Box Model you will see, that it is much easier to create tableless markup than tabled. BUT! Remember, tabled data should remain tabled.

4.2: FontEnd Optimization - Minimize downloads
We assume you already have a clean code.
Amount of external content downloads directly impact the page loading speed
Reasons of impact:
Amount of downloads, size of external content, ping to external resources, caching, loading way.

Why This Happens:
Exact reason of impact hides in visitor's browser. Every browser maintains it's own number of allowed concurrent connections to host and total concurrent connections.
This says if IE6(as today 0.6% of total users is nothing, but...) and IE7(1.9% users) allows 2 parallel connections to host, this says if you had 4 js, 2 css and 12 images (in css), browser should download all the content is html+18 files = 19 in total.
Quick calculation with latency 120ms can give us minimal page loading speed of 960ms (not included downloads times of content, that can be various). 1.080s, lets threat it as allowable.
Now we include the download of background (ex. image of 200kb optimized) and it's download time is 0.4s (400ms), page loading time becomes 1.5sec.
Too bad, we have to load 18 more files. Included JS libraries that can be "huge" as of web metrics of sizes. jQuery 150kb, various scripts (50kb), css 10kb, images for total of 500kb.
Lets calculate! Latency 120ms * 8 = 960ms + 120ms = 1.080s, js download time 0.220s, css 0.09s, images 0.8s in total we have page loading time 1.080+0.22+0.09+0.8= 2.2s.
Check browser concurrent connections amount at Browser Scope
Seems good? - Can be even faster! continue to read and i will teach how to...

Problem Solve:
Put all css in same file, for example user part in one css file, admin part for admin control panel in another. Just because there is no reason to load both styles to user in case the visitor will never see the admin control panel and so never use classes and/or ids from css file.

Put all JS into one or 2 files, for example scripts.js will contain all of inline scripting from the page and libs.js to store our libraries used on page. In case of using jquery or another famous libraries, prefered way to load directly from google. Benefits of this way i have already explained in separated article, you can read it here - Why using jQuery from Google Ajax API

Minimize image sizes: test various options in "Save for web" in Photoshop, try png8,png24,gif,jpeg. Watch for same quality but smallest image size.
Reduce Amount of Images:
Should you remove images from page and the page will become ugly? No! That is not the way of true front end ninjas:)
You should take All the images used in most of pages, such as back grounds, logos, footer icons, menu bullets, etc., and make one sprite so that you will receive one image and then maintain it's placements within CSS (background-position is a powerful method).
Minify Javascripts and CSS:
If you have the option to use minified libraries, definitely USE IT ! otherwise just minify the JS and CSS, nowadays there is a lot of resources online that can offer such service for free, Google It!
Compression for page speed:
In additional to reducing size of images, minifying JS and CSS, making sprites to reduce amount of images, we need to implement caching to reduce the size of contents even more.
GZIP compression: Nowadays everybrowser supports GZIPed content. Browser receives GZiped content from server and maintaining to render the page. I will not get deep inside the Gzip compression, but basic for our needs is here. GZip reduces contents weight for about 60-70% on the server and then content being Xfered to client(browser), not that bad at all.
GZip compression can be enabled on Web Server level (Apache,Nginx,IIS,LightHTTPD) or Server Side Language such as PHP/Perl.
Minify HTML
It is suggested to minify HTML, but care to save the source file separately, so you always can work on source (formatted properly), and then minify him and replace the previous. This may not save a lot of traffic, but pagespeed will rank you better.
Defer Javascript Parsing
Parsing Javascripts asynchronously, to not cause the browser to wait.
Why and how browser rendering javascript
Browser first scans all javascripts to see whether there present things such as redirects, etc., that can change browser behavior during page loading. To parse JS browser should download them and is blocking the page load. In-line javascripts executes in-line. Suggested way to load
I can suggest loading javascripts as google and facebook do... however this way not always works, test it before implementing on production servers.
In my example i use google's way as they also determine the protocol.
(function() {
    var scr = document.createElement('script'); 
    scr.type = 'text/javascript'; ga.async = true;
    scr.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.script-host.com/host.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(scr, s);
  })();

Avoid using @import in css
Avoid using @import rules in CSS, oherwise you will rank down by pagespeed insights.
Avoid bad requests
Keep in eye on the contents you load, don't allow broken links, not existed images, etc.
Correct order of javascript and css files
Stick to correct loading order of css and javascript.
Load CSS first, then javascript files. That is the right order.
Use properly sized image
This means do not use the images for example 100px X 100px, when you need it to be 20px X 25px, etc. This will save you a lot of traffic.
Specify Content Encoding
Specify server side content encoding rather than defining in HTML.
PHP Example



Sincerely, Valentin Ruskevych

No comments: