Presentation is loading. Please wait.

Presentation is loading. Please wait.

Best Practices for Speeding Up Your Web Site

Similar presentations

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

1 Best Practices for Speeding Up Your Web Site

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

3 1 2 3 4 5 6 1 2 3 4 5 6 Contents Content JavaScript Server Cookie CSS

4 Minimize HTTP Requests

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

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;}

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="" alt="Wikipedia" title="Wikipedia" /> </map>

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

9 Combine JavaScript

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

11 Reduce DNS Lookups (contd.)

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.

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

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

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

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.

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" />');

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.

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>

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

21 Put Scripts at Bottom Scripts block parallel downloads
<!-- content --> <script src=“script.js” …/> </body> </html> Inline scripts too

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

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

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

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.

26 Develop Smart Event Handlers (contd.)
<script> document.addEventListener("DOMContentLoaded", function(event) { console.log("DOM fully loaded and parsed"); }); </script>", "width": "800" }

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

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

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

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%

31 Gzip Components (contd.)

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 />';

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

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)

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.

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.

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.

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

40 Choose <link> Over @import
In 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.

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

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

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

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.

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.

46 Tools

47 Thank you!

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

Similar presentations

Ads by Google