Best Practices for Speeding Up Your Web Site 1.

47
Best Practices for Speeding Up Your Web Site http:// developer.yahoo.com 1

Transcript of Best Practices for Speeding Up Your Web Site 1.

Page 1: Best Practices for Speeding Up Your Web Site  1.

1

Best Practices for Speeding Up Your Web Site

http://developer.yahoo.com

Page 2: Best Practices for Speeding Up Your Web Site  1.

2

• 500 ms slower = 20% drop in traffic (Google)

• 100 ms slower = 1% drop in sales (Amazon)

• 400ms slower = 5-9% more people leave before the page finished loading (Yahoo)

Effect of Website Speed on Users

Page 3: Best Practices for Speeding Up Your Web Site  1.

3

Contents

1 Content1

2 JavaScript23 Server3

445

Cookie

5 CSS

6 Images6

Page 4: Best Practices for Speeding Up Your Web Site  1.

4

Minimize HTTP Requests

Page 5: Best Practices for Speeding Up Your Web Site  1.

5

Minimize HTTP Requests (contd.)

• 80% of the end-user response time is spent on the front-end. Most of this time is tied up in downloading all the components in the page: images, stylesheets, scripts, Flash, etc.

• The more images, scripts, CSS, Flash, etc that your page has the more requests will be made and the slower your pages will load.

• Combined files :  are a way to reduce the number of HTTP requests by combining all scripts into a single script, and similarly combining all CSS into a single stylesheet, combine images into CSS sprites ( top 10 popular web - 7 scripts and 2 stylesheet)– CSS Sprites – Image maps– Inline images

Page 6: Best Practices for Speeding Up Your Web Site  1.

6

CSS Sprites

• When you combine most or all of your images into a sprite, you turn multiple images requests into just one. Then you just use the background-image, and background-position CSS property to display the section of the image you need

#home{left:0px;width:46px;}#home{background:url('img_navsprites_hover.gif') 0 0;}#home a:hover{background: url('img_navsprites_hover.gif') 0 -45px;}

http://www.w3schools.com/css/tryit.asp?filename=trycss_sprites_hover_nav

Page 7: Best Practices for Speeding Up Your Web Site  1.

7

Image Maps• Combine multiple images into a single image. The overall

size is about the same, but reducing the number of HTTP requests speeds up the page. Image maps only work if the images are contiguous in the page, such as a navigation bar. Defining the coordinates of image maps can be tedious and error prone. Using image maps for navigation is not accessible too, so it's not recommended.

<img src="image.png" alt="Website map" usemap="#mapname" /> <map name="mapname"> <area shape="rect" coords="9,372,66,397" href="http://en.wikipedia.org/" alt="Wikipedia" title="Wikipedia" /> </map>

• http://en.wikipedia.org/wiki/The_Club_(Literary_Club)

Page 8: Best Practices for Speeding Up Your Web Site  1.

8

Inline images

• Inline images use the data: URL scheme to embed the image data in the actual page. This can increase the size of your HTML document. Inline images are not yet supported across all major browsers

• <img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/ /ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7" >

Page 9: Best Practices for Speeding Up Your Web Site  1.

9

Combine JavaScript

Page 10: Best Practices for Speeding Up Your Web Site  1.

10

Reduce DNS Lookups• The Domain Name System (DNS) maps hostnames to IP

addresses.• It typically takes 20-120 milliseconds for DNS to lookup

the IP address for a given hostname. The browser can't download anything from this hostname until the DNS lookup is completed.

• DNS lookups are cached for better performance (ISP server cache,OS,browser).

• When the client's DNS cache is empty, the number of DNS lookups is equal to the number of unique hostnames in the web page. Reducing the number of unique hostnames reduces the number of DNS lookups.

• Reducing the number of unique hostnames has the potential to reduce the amount of parallel downloading that takes place in the page. Avoiding DNS lookups cuts response times, but reducing parallel downloads may increase response times

Page 11: Best Practices for Speeding Up Your Web Site  1.

11

Reduce DNS Lookups (contd.)

Page 12: Best Practices for Speeding Up Your Web Site  1.

12

Avoid Redirects• URL redirects are made using HTTP status codes 301 and

302. They tell the browser to go to another location

• Inserting a redirect between the user and the final HTML document delays everything on the page since nothing on the page can be rendered and no components can be downloaded until the HTML document arrives.

Page 13: Best Practices for Speeding Up Your Web Site  1.

13

Make Ajax Cacheable• Ajax Caching Is The Same As HTTP Caching

• Some of the other rules also apply to Ajax:– Gzip Components– Reduce DNS Lookups– Minify JavaScript– Avoid Redirects– Configure ETags

Page 14: Best Practices for Speeding Up Your Web Site  1.

14

Split Components Across Domains• Maximize parallel downloads. But not more than 2-4 domains, because of the DNS lookup penalty

• www.example.org – HTML content• static.example.org – Static components

• number of aliases: 1, 2, 4, 5, and 10. This increases the number of parallel downloads to 2, 4, 8, 10, and 20 respectively

Page 15: Best Practices for Speeding Up Your Web Site  1.

15

Minimize the Number of iframes

• <iframe> pros:– Can help with slow third-party content like badges and

ads– Security sandbox– You can download scripts in parallel

• <iframe> cons:– They have a cost even if blank– They block page onload– Non-semantic

Page 16: Best Practices for Speeding Up Your Web Site  1.

16

No 404’s

• Making an HTTP request and getting a useless response

• Particularly bad is when the link to an external JavaScript is wrong and the result is a 404. First, this download will block parallel downloads. Next the browser may try to parse the 404 response body as if it were JavaScript code, trying to find something usable in it.

Page 17: Best Practices for Speeding Up Your Web Site  1.

17

Post-load Components

• What's absolutely required in order to render the page initially?

• The rest of the content and components can wait.

Initial DOM:<div id="images-slide"> <img src="img/1.jpg" /> </div>Onready Javascript:var $sl = $('#images-slide');$sl.append('<img src="img/2.jpg" />'); $sl.append('<img src="img/3.jpg" />'); $sl.append('<img src="img/4.jpg" />');

Page 18: Best Practices for Speeding Up Your Web Site  1.

18

Preload Components

• By preloading components you can take advantage of the time the browser is idle and request components (like images, styles and scripts) you'll need in the future.

• There are actually several types of preloading:- Unconditional preload - as soon as onload fires, you go ahead and fetch some extra components. - Conditional preload - based on a user action you make an educated guess where the user is headed next and preload accordingly.- Anticipated preload - preload in advance before launching a redesign.

Page 19: Best Practices for Speeding Up Your Web Site  1.

19

Reduce the Number of DOM Elements

• A complex page means more bytes to download and it also means slower DOM access in JavaScript. It makes a difference if you loop through 500 or 5000 DOM elements on the page when you want to add an event handler for example.

Use:<ul id="navigation-main"> etc.. </ul>in stead of:<div id="navigation-main">

<ul> etc.. </ul> </div>

Page 20: Best Practices for Speeding Up Your Web Site  1.

20

Minimize DOM Access

• Accessing DOM elements with JavaScript is slow so in order to have a more responsive page, you should:- Cache references to accessed elements- Update nodes "offline" and then add them to the tree- Avoid fixing layout with JavaScript

Page 21: Best Practices for Speeding Up Your Web Site  1.

21

Put Scripts at Bottom• Scripts block parallel downloads • <!-- content -->

<script src=“script.js” …/></body></html>

• Inline scripts too

Page 22: Best Practices for Speeding Up Your Web Site  1.

22

Make JavaScript and CSS External• JavaScript and CSS files are cached by the browser.

• JavaScript and CSS that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the size of the HTML document is reduced without increasing the number of HTTP requests

Page 23: Best Practices for Speeding Up Your Web Site  1.

23

Minify JavaScript and CSS

• Minification is the practice of removing unnecessary characters from code to reduce its size thereby improving load times.

• When code is minified all comments are removed, as well as unneeded white space characters (space, newline, and tab)

• In the case of JavaScript, this improves response time performance because the size of the downloaded file is reduced

• YUI Compressor

Page 24: Best Practices for Speeding Up Your Web Site  1.

24

Remove Duplicate Scripts

• Creating unnecessary HTTP requests and wasted JavaScript execution

• CSS : update in Chrome & FireFox & IE 9

• Javascript : update in Chrome & IE 9

Page 25: Best Practices for Speeding Up Your Web Site  1.

25

Develop Smart Event Handlers• Don't wait for onload, use DOMContentLoaded (HTML5)

• The DOMContentLoaded event fires when parsing of the current page is complete; the load event fires when all files have finished loading from all resources, including ads and images

• Too many event handlers attached to different elements of the DOM tree which are then executed too often.

•  If you have 10 buttons inside a div, attach only one event handler to the div wrapper, instead of one handler for each button. Events bubble up so you'll be able to catch the event and figure out which button it originated from.

Page 26: Best Practices for Speeding Up Your Web Site  1.

26

• <script> document.addEventListener("DOMContentLoaded", function(event) { console.log("DOM fully loaded and parsed"); }); </script>

• http://ie.microsoft.com/testdrive/HTML5/DOMContentLoaded/

Develop Smart Event Handlers(contd.)

Page 27: Best Practices for Speeding Up Your Web Site  1.

27

Use a Content Delivery Network (CDN)

• For static components• Content closer to your users• Akamai, Amazon CloudFront

Page 28: Best Practices for Speeding Up Your Web Site  1.

28

Add Expires or Cache-Control Header

For static components• “Never expire” policy, far future Expires header• Once a component is served, the browser never asks

for it again• When you need to change a component, rename it• Apache example:

ExpiresActive On ExpiresDefault "modification plus 10 years" ExpiresByType text/css "access plus 2 months“

For dynamic components• Use Cache-control• Cache-control: max-age=86400

Page 29: Best Practices for Speeding Up Your Web Site  1.

29

Configure ETags• ETags are meant to help with caching• A component served from server A has a different ETag

than the same component served from B• Configure ETags not to include inode• … or just remove them and implement “never expire”

policy

• Apache default FileETag INode MTime Size • FileETag None to remove

Page 30: Best Practices for Speeding Up Your Web Site  1.

30

Gzip Components• You send zipped content over the wire, the browser

unpacks it

• Modern browsers understand compressed content

• Request header• Accept-Encoding: gzip,deflate

• Response header• Content-Encoding: gzip

• All text components should be sent gzipped: html (php), js, css, xml, txt…Image and PDF files should not be gzipped because they are already compressed

• Gzipping generally reduces the response size by about 70%

Page 31: Best Practices for Speeding Up Your Web Site  1.

31

Gzip Components (contd.)

Page 32: Best Practices for Speeding Up Your Web Site  1.

32

Flush Buffer Early• Let the browser start fetching components while your

backend is busy• PHP has the function flush()• Best for busy backends / light frontends• echo 'Begin ...<br />'; for( $i = 0 ; $i < 10 ; $i++ ) { echo $i . '<br />'; flush(); ob_flush(); sleep(1); } echo 'End ...<br />';

Page 33: Best Practices for Speeding Up Your Web Site  1.

33

Use GET for Ajax Requests

• POST is a two-step process (send headers, send data)

• GET request is one TCP packet (unless you have a lot of cookies)

• Max URL length 2K (because of IE)

• POST without actually posting data is like GET

Page 34: Best Practices for Speeding Up Your Web Site  1.

34

Avoid Empty Image src• HTML5 eli mi nates this prob lem• <img src=""> (HTML)     • var img = new Image(); img.src = ""; (JavaScript)     • style="background-image:url();" (CSS)

Page 35: Best Practices for Speeding Up Your Web Site  1.

35

Use Cookie-Free Domains for Components

• When the browser makes a request for a static image and sends cookies together with the request, the server doesn't have any use for those cookies. So they only create network traffic for no good reason. You should make sure static components are requested with cookie-free requests. Create a subdomain and host all your static components there.

• The idea of cookieless domains is to have static resources (that is.. files that rarely/never change, regardless of session state, etc) served without the browser having to send cookie data (which is useless to static content anyway).

• Yahoo! uses yimg.com, YouTube uses ytimg.com, Amazon uses images-amazon.com and so on.

Page 36: Best Practices for Speeding Up Your Web Site  1.

36

Use Cookie-Free Domains for Components (contd.)

Page 37: Best Practices for Speeding Up Your Web Site  1.

37

Reduce Cookie Size

• Eliminate unnecessary cookies.

• Keep cookie sizes as low as possible to minimize the impact on the user response time.

• Be mindful of setting cookies at the appropriate domain level so other sub-domains are not affected.

Page 38: Best Practices for Speeding Up Your Web Site  1.

38

Put Stylesheets at Top

• Place the stylesheets as early as possible in the document

<head> <title>My page</title> <link href=“styles.css” …/></head><body> <!-- content -->

•  While researching performance at Yahoo!, it was discovered that moving stylesheets to the document HEAD makes pages appear to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively.

Page 39: Best Practices for Speeding Up Your Web Site  1.

39

Avoid CSS Expressions

• CSS expressions are a powerful (and dangerous) way to set CSS properties dynamically. They were supported in Internet Explorer starting with version 5, but were deprecated in Internet Explorer 8, and not supported by other browsers.

• Background-color: expression( (new Date()).getHours()%2 ? "#B8D4FF" : "#F08A00" );

Page 40: Best Practices for Speeding Up Your Web Site  1.

40

Choose <link> Over @import

• In IE @import is the same as putting <link> at the bottom

• For instance, if first.csscontains the following

content: @import url("second.css")

The browser must download, parse, and execute first.css before it is able to discover that it needs to download second.css.

Page 41: Best Practices for Speeding Up Your Web Site  1.

41

Avoid Filters

• IE proprietary AlphaImageLoader • Fixes an IE6 problem with semi-transparent PNGs, IE7 is

fine• Blocks rendering, freezes the browser• Increased memory consumption • Per element, not per image!Best: Avoid completely, use gracefully degrading PNG8Fallback: use underscore hack _filter not to penalize IE7+

users

#some-element { background: url(image.png);_filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='image.png',sizingMethod='crop');}

Page 42: Best Practices for Speeding Up Your Web Site  1.

42

Optimize Images

• Use PNGs instead of GIFs• Strip comments (meta data)• Tools : pngcrush, imagemagick, jpegtran …

Page 43: Best Practices for Speeding Up Your Web Site  1.

43

Optimize CSS Sprites• Choose horizontal over vertical when possible• Combine similar colors • Keep color count low (<256) to fit in a PNG8• “Be mobile-friendly”

– Don’t leave big gaps– This doesn't affect the file size as much but requires

less memory for the user agent to decompress the image into a pixel map

Page 44: Best Practices for Speeding Up Your Web Site  1.

44

Do Not Scale Images in HTML

• Don't use a bigger image than you need just because you can set the width and height in HTML.

• If you need <img width="100" height="100" src="mycat.jpg" /> then your image (mycat.jpg) should be 100x100px rather than a scaled down 500x500px image.

Page 45: Best Practices for Speeding Up Your Web Site  1.

45

Make favicon.ico small and cacheable

• Browser request it, so it's better not to respond with a 404 

• So to mitigate the drawbacks of having a favicon.ico

make sure:– It's small, preferably under 1K.– Set Expires header.

Page 47: Best Practices for Speeding Up Your Web Site  1.

47

Thank you!