Presentation is loading. Please wait.

Presentation is loading. Please wait.

Best Practices for Speeding Up Your Web Site 1.

Similar presentations

Presentation on theme: "Best Practices for Speeding Up Your Web Site 1."— Presentation transcript:

1 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) 2 Effect of Website Speed on Users

3 Contents Content JavaScript Server Cookie CSS Images 3

4 Minimize HTTP Requests 4

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 5

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') px;} 6

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

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 8

9 Combine JavaScript 9

10 Reduce DNS Lookups The Domain Name System (DNS) maps hostnames to IP addresses. It typically takes 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 10

11 Reduce DNS Lookups (contd.) 11

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

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 13

14 Split Components Across Domains Maximize parallel downloads. But not more than 2-4 domains, because of the DNS lookup penalty – HTML content – 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 14

15 Minimize the Number of iframes pros: – Can help with slow third-party content like badges and ads – Security sandbox – You can download scripts in parallel cons: – They have a cost even if blank – They block page onload – Non-semantic 15

16 No 404s 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. 16

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: img/1.jpg Onready Javascript: var $sl = $('#images-slide'); $sl.append(' '); 17

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

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: etc.. in stead of: etc.. 19

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 20

21 Put Scripts at Bottom Scripts block parallel downloads Inline scripts too 21

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 22

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 23

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 24

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

26 document.addEventListener("DOMContentLoaded", function(event) { console.log("DOM fully loaded and parsed"); }); MContentLoaded/ MContentLoaded/ Develop Smart Event Handlers (contd.) 26

27 Use a Content Delivery Network (CDN) For static components Content closer to your users Akamai, Amazon CloudFront 27

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=

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 29

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

31 Gzip Components (contd.) 31

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... '; for( $i = 0 ; $i < 10 ; $i++ ) { echo $i. ' '; flush(); ob_flush(); sleep(1); } echo 'End... '; 32

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 33

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

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, YouTube uses, Amazon uses and so on. 35

36 36 Use Cookie-Free Domains for Components (contd.)

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

38 Put Stylesheets at Top Place the stylesheets as early as possible in the document My page 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. 38

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" ); 39

40 Choose In is the same as putting at the bottom For instance, if first.csscontains the following 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. 40

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 PNG8 Fallback: 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'); } 41

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

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 – Dont 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 43

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 then your image (mycat.jpg) should be 100x100px rather than a scaled down 500x500px image. 44

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

46 Tools 46

47 Thank you! 47

Download ppt "Best Practices for Speeding Up Your Web Site 1."

Similar presentations

Ads by Google