frontend performance

23
Frontend performance Best practices for speeding up your website

Upload: alaa-batayneh

Post on 17-Dec-2014

7.797 views

Category:

Technology


6 download

DESCRIPTION

Frontend performance tips to boost your website load time

TRANSCRIPT

Page 1: Frontend performance

Frontend performanceBest practices for speeding up your website

Page 2: Frontend performance

Fact• Only 10–20% of the end user response time is spent

downloading the HTML document. The other 80–90% is spent downloading all the components in the page.

• If you want to dramatically reduce the response times of your web pages, you have to focus on the other 80–90% of the end user experience. What is that 80–90% spent on ?How can it be reduced?

Page 3: Frontend performance

Best practices rules - Content

1. Make fewer HTTP RequestsAbout HTTP requests -Content-Encoding (compression)-If-Modified-Since (conditional GET)-Expires: Wed, 05 Oct 2022 19:16:20 GMT--Connection: Keep-Alive

•Image Maps•CSS Sprits•Inline Images (data:URL/ fie_get_contents / encode data with MIME base64) e.g .cart { background-image: url(data:image/gif;base64, <?php echo base64_encode(file_get_contents("../images/cart.gif")) ?>);}

•Combine JS and CSS

Page 4: Frontend performance

Best practices rules - Content

2. Reduce DNS lookups•DNS takes 20.120 milliseconds for DNS to lookup the IP address for a given hostname•ISP/browserscache DNS lookups

• IE Cache expiration (30 mins)• FF Cache expiration (1 min)• IE keep-alive (1 min)• FF keep.alive (5 mins)

•If cache is empty then number of DNS lookups = unique hostnames (URL, images, flash …etc)•Reduce number of unique hostnames reduces the amount of parallel downloads.•Reduce parallel downloads increase response time•TTL; DNS record returns from lookup TTL value which tells the client how long the record can be cached.•Use Keep-Alive to use existing connections and fewer domains

To flush DNS cacheLinux (/etc/init.d/nscd restart)Mac OS X (dscacheutil --flushcache)

Page 5: Frontend performance

Best practices rules - Content

3. Avoid RedirectsHTTP/1.1 301 Moved PermanentlyLocation : http://example.comContent-Type: text/html

•One of the most wastfull redirects is caused by the trailing slashhttp://indemajtech.net/contact results in 301 respons to http://indemajtech.net/contact/But this is fixed in Apache by using Alias or mod_rewrite or DirectorySlash if you use Apache handlers.

•See CNAME if you are using multiple HTTP servers with different names on same physical host (alias for pointing one domain to another)

Page 6: Frontend performance

Best practices rules - Content

4. Remove Duplicate Scripts

•Unnecessary HTTP requests caused by extra js get requests increases load time.•One good way to overcome this is using a script management system in your template system

•Drupal e.g.•In template .info file scripts[] = fly.js•In module drupal_add_js

Page 7: Frontend performance

Best practices rules - Content

5. Make Ajax cacheable

To improve performance, optimize Ajax responses and make them cacheable•Add Expires or Cache-Control headers•Gzip components•Reduce DNS Lookups•Minify JS•Avoid Redirects•Configure ETags

Page 8: Frontend performance

Best practices rules - Content

6. Post-load ComponentsWhich component can wait to be loaded later.•YUI Image Loader which allows you to delay images•YUI Get Utility; get JSand CSS on the fly

7. Pre-load ComponentsWait for idle browser state and request components that you might need in other pagesTypes1.Unconditional preload; once the page is loaded, fetch extra components2.Conditional preload; user action based 3.Anticipated preload; preload in advance

Page 9: Frontend performance

Best practices rules - Content

7. Reduce number of DOM Elements

High number of DOM elements means that something should be improved with markup of page.Nested Tables ? Divs to fix layout issuesYUI CSS utility which contains CSS reset.

To get number of DOM elements type in Firebug consoleDocument.getElementByTagName(‘*’).length

8. Split components across domainsSo you can maximize parallel downloads, make sure not to use 2-4 domains (DNS lookup)Dynamic content on example.com, static on static1.example.com, static2.example.com

Page 10: Frontend performance

Best practices rules - Content

9. Minimize number of iframesPros•Third party content•Security•Download scripts in parallel

Cons•Resources•Block page onload•Non-semantic (how document supposed to look rather than its structure)

Page 11: Frontend performance

Best practices rules - Content

10. No 404sExtra HTTP requestsAlternatives ?

Page 12: Frontend performance

Best practices rules - Server

1. User CDNCollection of web servers distributed across multiple locations to deliver content more efficiently to users

2. Add an Expires or Cache-Control headerStatic Content; never expireDynamic content; cache-control (conditional requests)

3. Gzip componentsGzipping reduce response size by about %70 (Apache1.3 mod_gzip/ Apache2.x mod_deflate)Server chooses what to gzip (html/xml/json) and what not to gzip (pdf/images)

Page 13: Frontend performance

Best practices rules - Server

4. Configure Entity Tags (ETags)Mechanism that web servers and browsers use to determine whether the component/entity in the browser’s cache matches the one on the origin server (image/js file/css file).

Etags is a more flexible mechanism than last-modified dateEtag is a string identifying version of componentLast-modified: validate based on timestampEtag: ’10c23bs-4ab-45345f2a’

Drowback of Etags is it typically constructed on a specific server hosting a site and wont match on another server

If you are not taking advatages, disable it from Apache config file because it increases the size of HTTP headers in response and requests.FileETag none // in apache config files

Page 14: Frontend performance

Best practices rules - Server

5. Flush the Buffer Early•On page request the backend needs around 200-500ms to stitch together your HTML page, during this time the browser is idle.•In PHP you have function flush() which allows sending partically ready HTML to the browser while your backend is busy collection more component.•Best place to consider flush() is your HTML HEAD tag

6. Use GET for Ajax requestsPOST request happen in 2 steps: send headers, send dataGET request takes on TCP packet to send

7. Avoid empty image scrRead Empty Image src can destroy your site

Page 15: Frontend performance

Best practices rules – Cookies

1. Reduce cookie size•Eliminate unnecessary cookies•Apply cookies to domains NOT subdomains•Set Expires date

2. Use cookie-free domains for componentsWhen a browser request a static image and sends a cookie with the request, the server does not use that cookie, so its only no good for traffic, you should make static components cookie-free request

Create a subdomain to host all your static data, that way *.example.com uses the example.com cookie

Omitting www from your domain oblige you to write cookies to *.example.comSo for better performance use www subdomain.

Page 16: Frontend performance

Best practices rules - CSS1. Put CSS at topMoving css to the head makes pages appear loading faster because the page is rendering progressively.

2. Avoid CSS expressionsCSS expressions are used to set CSS properties dynamicallyCSS Expressions accept JS expressionsBackground-color: expression( (new Data()).getHours()%2 ? ‘red’ : ‘black’ );Width: expression( document.body.clientWidth < 600 ? ‘600px’ : ‘auto’);

Drawbacks Expressions evaluated on page render, resize, scroll, mouse over …etc.Moving the mouse a little bit can generate more than 10,000 evaluationTo reduce CSS expressions evaluations user one-time

Background-color: expression(altBgColor(this));<script>Function altBgColor(element) {

elm.style.backgroundColor = (new Data()).getHours()%2 ? ‘red’ : ‘black’ );}</script>

Page 17: Frontend performance

Best practices rules - css

3. Choose <link> over @import

4. Avoid FiltersIE-Proprietary AlphaImageLoader and others increase memory consumption and its applied per element not per image.

Solve this and user http://css3pie.com

Page 18: Frontend performance

Best practices rules - JS

1. Put JS at the bottomScripts block parallel downloadsWe cannot put document.write at the bottom We can use DEFER attribute to indicate that the script does not contain document.write (FF don’t support, IE does)

<script type=‘text/javascript’ src=‘fly.js’ defer=‘defer’></script>

2. Make Javascripts and CSS externalUsing external files (not inline) of JS and CSS generally produces faster pages because JS and CSS are cached by the browser.While inline JS and CSS are loaded on each page load

Page 19: Frontend performance

Best practices rules - JS

3. Minify JS and CSSMinifying removes unnecessary characters to reduce size (remove all comments, white spaces)Minifying tools JSMin and YUI compressor

4. Remove Duplicate Scripts•Unnecessary HTTP requests caused by extra js get requests increases load time.•One good way to overcome this is using a script management system in your template system

5. Minimize DOM AccessAccessing DOM elements with JS is slowRead http://yuiblog.com/blog/2007/12/20/video-lecomte/

Page 20: Frontend performance

Best practices rules - JS

6. Develop smart event handles•Attaching too many event handles to DOM elements might make pages less responsive•Event delegation/bubbling is a bingo; whenever you do something to an element, the elements tell parent elements or a like elements about it

Page 21: Frontend performance

Best practices rules - Images

1. Optimize Images•Use PNGs rather than GIFs•Run pngcrush on all your PNGS http://pmt.sourceforge.net/pngcrush/•Run jpegtran on all your JPEGs http://jpegclub.org/

2. Optimize CSS Sprits•Arrange sprites horizontally rather than vertically reduce small size file•Don’t leave big gaps between image, this does not impact the file size, but requires less momory to decompress the image into a pixel map

3. Don’t scallimages in HTML4. Make favicon.ico small and cacheable•Under 1K•Imagemagick can help you create small favicons http://www.imagemagick.org

Page 22: Frontend performance

Best practices rules – Mobile

1. Keep components under 25k• iPhone wont cache components bigger that 25K• Performance Reasearch, Part 5: iPhone cacheability

2. Pack components into multipart documentPacking components into multipart document is like an email with attachement, it helps

fetching several components with one HTTP request.

Page 23: Frontend performance

Thank you

Alaa H Batayneh

http://batayneh.me