HTML CSS & Javascript

7,647 views

Published on

Best practices and optimization techniques

Published in: Technology

HTML CSS & Javascript

  1. 1. HTML / CSS / JS Best practices and optimization techniques
  2. 2. Fi (Fantasy Interactive) www.f-i.com david.lindkvist@f-i.com 2
  3. 3. Why are we here? The web is slowly moving towards using open standards HTML, CSS and Javascript is the new Flash (Silverlight anyone?) Javascript performance has doubled in the past few years More and more application logic end up in the UI HTML, CSS and JS are VERY forgiving - we need solid conventions to build on 3
  4. 4. Agenda HTML CSS Javascript & jQuery Performance optimizations Visual optimizations 4
  5. 5. Semantic Markup Use correct tag to describe your content H1, H2, H3 tags for headings OL, UL, DL for ordered, unordered, and definition lists P tags for paragraphs Pages immediately become more accessible, both for search engines, and humans alike (such as a user who need to use a screen reader) 5
  6. 6. Semantic Markup - naming header, topNavigation, sidebarNavigation, leftColumn, rightColumn, footer... sounds familiar? Avoid using names that describe position... think content! brandingArea, mainNavigation, subNavigation, mainContent, sub content, siteInfo CSS can change position of your content! 6
  7. 7. Keep it clean! Try not to bloat your markup with unnecessary elements or CSS classes. Avoid using extra block elements just for positioning - change to display:block on inline elements instead. Use the cascading functionality in CSS instead of adding unnecessary classes 7
  8. 8. A case of div-itis <div class="content"> <p> Lorem ipsum dolor sit amet dolor adispiscing elit. </p> </div> <div class="featureList"> <ul> <li class="redBullet">Dog</li> <li class="redBullet">Cat</li> <li class="redBullet">Mouse</li> </ul> </div> 8
  9. 9. A case of class-itis <p class="content" > Lorem ipsum dolor sit amet dolor adispiscing elit. </p> <ul class="featureList" > <li class="redBullet">Dog</li> <li class="redBullet">Cat</li> <li class="redBullet">Mouse</li> </ul> 9
  10. 10. Clean and simple markup! <p> Lorem ipsum dolor sit amet dolor adispiscing elit. </p> <ul class="redBullets" > <li>Dog</li> <li>Cat</li> <li>Mouse</li> </ul> 10
  11. 11. CSS - Words of advice Aim for readable, maintainable code (leave the complex shorthand to the CSS compression algorithms) Use the cascade! That’s what it’s there for. Be mindful of CSS selectors pseudo-classes and properties which aren’t available to all browsers (IE6 is going to be your enemy most of the time) Class names should NOT BE CHAINED. IE6 does not support this: “div.classnameA.classnameB {” Check changes in all browsers as you make the changes — not once you’re 90% “done” 11
  12. 12. CSS - The Cascade Sorts by origin and importance 1. inline style -> 2. embedded stylesheet -> 3. linked stylesheet A style rule with higher importance wins over identical rules with lower importance Sorts by specificity of the CSS selector Notes: If 2 or more rules have the same importance, origin and specificity, the last one wins The browsers default style sheet is treated as if it’s an imported stylesheet imported before all other 12
  13. 13. Use a reset stylesheet All browsers have a default stylesheet Resets default view behaviors of many HTML elements to display uniformly across all browsers Include as first external stylesheet Example: Popular reset stylesheets Eric Meyer’s reset.css YUI reset.css 13
  14. 14. CSS - File structure Choose a file structure that makes sense for your project! Some larger projects benefits from a more separated approach: reset.css typography.css layout.css gui.css Other projects may be fine using one single stylesheet 14
  15. 15. CSS - ID your body Flexibility to apply page specific styles without adding separate stylesheets </head> <body id=”contactPage”> Override default style using the body ID: a { color: blue; } #contactPage a { color: red; } 15
  16. 16. CSS - Sliding Doors Create dynamic length graphics for buttons, tabs and menu items Use 2 nested elements and slide background images over each other <a href=”#”><span>Text</span></a> <span> <a> left side Text right side 16
  17. 17. CSS image sprites Contain several different graphics in one file WHY? Reduces number of HTTP calls to server No “flicker” when first rolling over item with hover state. Modifying CSS background-position is instant! Example: button sprites 17
  18. 18. Tips when using image sprites Expect sprites to grow—group/space items accordingly Place sprites on even multiples (50px, 100px, 500px) Avoid using string values for positioning (ie, “top”, “left”, “right”, etc.). Pixels are preferred when specifying the background position for all sprites Except in the case of the sliding-doors technique. Here, a value of 100% is necessary. 18
  19. 19. Tips when using image sprites If using the ‘background: ...’ CSS shorthand, enter ALL values in their PROPER order: 1. background-color: transparent | color 2. background-image: none | url(path/to/image.jpg) 3. background-repeat: no-repeat | repeat | repeat-x | repeat-y 4. background-attachment: scroll | fixed 5. background-position: 0px 0px Example: background: transparent url(../assets/sprite_main.png) no- repeat scroll 0px -50px; 19
  20. 20. Tips when using image sprites Keep PSDs of the sprites up-to-date Remember that global light settings get reset to the default of 120°— double check the drop shadows with the original design, most designers prefer to use 90°!!! GIFs and PNGs optimize horizontally Experiment with compression settings. Often times, PNG-8 will be smaller. 20
  21. 21. PNG optimization PNG was developed as an open-source replacement for GIF Introduced new features for compression Photoshop don’t offer any optimization options PNG-24 Truecolor PNG-8 Indexed-color PNG’s are not “unoptimizable”! 21
  22. 22. GIF compression Each number represents a unique color GIF compress horizontally, thus an image like this will not compress well: 22
  23. 23. PNG Scanline filtering (delta filters) 2 represents applied filter “UP” “For the current pixel take the value of the above pixel and add it to the current value.” 23
  24. 24. PNG Scanline filtering (delta filters) 1 represents applied filter “SUB” “Take the value of the left pixel and add it to the current value.” 24
  25. 25. PNG Scanline filtering (delta filters) 1 represents applied filter “SUB” “Take the value of the left pixel and add it to the current value.” 25
  26. 26. PNG optimization Compression utilities can help us: Pick up best image type (truecolor, indexed-color) Pick up best delta filters (5 delta filters to select from) Pick up best compression strategy All these operations does NOT affect image quality! One of the best compression services: http://www.gracepointafterfive.com/punypng But where is the command line script? 26
  27. 27. Progressive Enhancement The web was using Graceful Degradation Target most advanced browsers, apply fixes to older browsers Moving towards Progressive Enhancement Focus on the content! 1. Begin with semantic markup 2. Apply basic style using CSS 3. Transform into richer user experience using JS and CSS Examples: Atari.com Alkoholprofilen.se 27
  28. 28. Javascript namespaces Stay away from the global namespace to avoid collisions with 3rd party code Wrap all functions in a namespace object: var myNamespace = {}; myNamespace.myFunction = function () { // I’m not a global function and I like it }; Example: Atari.com global.js 28
  29. 29. jQuery - Sizzle selectors jQuery includes the Sizzle CSS selector engine from version 1.3 The syntax goes something like this: $(String selector, DOMElement context); Example: var myList = $(‘#myList’); $(‘li’, myList); Supports CSS3 selectors 29
  30. 30. jQuery - Chain selectors Requires 3 DOM traversals: $(‘#mydiv’).html(‘Hello World!’); $(‘#mydiv’).css(‘border’, ‘1px solid black’); $(‘#mydiv’).fadeIn(‘fast’); Requires 1 DOM traversal: $(‘#mydiv’).html(‘Hello World!’).css(‘color’, ‘red’).fadeIn(‘fast’); OR var myDiv = $(‘#mydiv’); myDiv.html(‘Hello World!’); myDiv.css(‘color’, ‘red’); myDiv.fadeIn(‘fast’); 30
  31. 31. jQuery - Chain selectors Not visually stunning! But... ... cuts down on DOM traversal and hundreds of internal calls: $(‘#mydiv’) .html(‘Hello World!’) .children(‘p’) .css(‘color’, ‘red’) .end() .css(‘background-color’, ‘#ffdead’); This chain will dip into its children, and the end() method will end the chain, reverting to the initial selector 31
  32. 32. jQuery - Plugin Pattern jQuery offers a mechanism to extend it with plugins Most internal methods and functions are written using this pattern Helps us build reusable components Should be easy to override default properties 32
  33. 33. jQuery - Plugin Pattern All new methods are attached to the jQuery.fn object, all functions to the jQuery object. inside methods, 'this' is a reference to the current jQuery object. Any methods or functions you attach must have a semicolon (;) at the end or compressed code will break Your method must return the jQuery object You should use this.each to iterate over the current set of matched elements Always attach the plugin to jQuery directly instead of $, so users can use a custom alias via noConflict(). 33
  34. 34. Example plugin pattern Template example: The Fi plugin pattern Real world example: The Fi checkbox plugin 34
  35. 35. Page specific Javascript Inline script Dynamic config vars that may change for each page load External scripts page-specific javascript file Used to load plugins Override plugin defaults with config variables EXAMPLE: load and configure labelinput plugin 35
  36. 36. Qunit Latest version does not rely on jQuery Example: checkbox plugin unit test Testswarm.com 36
  37. 37. JS logging alert() console.log() Blackbird JS http://www.gscottolson.com/blackbirdjs/ Example: Creating an abstract jQuery log function to wrap any logger utility. 37
  38. 38. Optimize page load Use external resources not inline JS/CSS External files will be cached and minimizes document size CSS at the top JS at the bottom 38
  39. 39. Javascript files always block! Blocks render because they might document.write() Downloads sequentially 39
  40. 40. Skip document.ready() Will only fire once all external resources has been loaded. External scripts from third parties like Google Analytics cause long delays (~1s) before event fires Put script in correct order at bottom of page Put analytics code last! WARNING! Requires a solid file structure 40
  41. 41. Example - Load order <head> reset.css layout.css </head> <body> <!-- document markup --> jquery.js jquery.checkbox.js global.js page-home.js google-analytics.js </body> 41
  42. 42. Optimize load time Compress external resources! CSS compressor (YUICompressor, CSSTidy) JS compressor (JSmin, YUICompressor, etc) GZIP server response Example: YUICompressor and GZIP size comparisons 42
  43. 43. JSLint Your Code What’s JSLint? Looks for problems in Javascript code It’s a code quality tool A Javascript syntax checker and validator Prevents errors occurring from compressing files! Looks at style conventions and structural problems that may cause problems WARNING: JSLint will hurt your feelings! 43
  44. 44. JSLint Recommended options 1. In the “Options” box, click “The Good Parts” 2. Uncheck “Allow one var statement per function” 3. Check “Assume a browser” 4. Uncheck “Disallow ++ and --” 5. Uncheck “Require ‘use strict;’” (ECMAScript 5 strict mode) unless you actually test in a strict browser http://www.jslint.com EXAMPLE: JSlint Checbox plugin 44
  45. 45. Reduce number of HTTP requests Biggest impact on end-user response times is the number of page components With an empty cache, each external component requires a new HTTP request Can’t the browser download all files in parallel? HTML/1.1 spec. suggests max 2 simultaneous downloads per hostname 45
  46. 46. How do we reduce number of HTTP requests? Merge common files Global Javascript files Global stylesheets Use CSS image sprites! 46
  47. 47. Automated build script Let the ANT do the work! (or any other build tool) 1. merge common files 2. compress merged files EXAMPLE: Ant build script 47
  48. 48. Maximize parallel downloads Most browsers only download 2 files from same domain in parallel 2-4 domains give optimal performance Remember: Javascripts are usually downloaded and parsed sequentially EXAMPLE: Panamera Family Tree - 1 vs 4 domains 48
  49. 49. Maximize parallel downloads Downloading 2 components in parallel using 1 hostname 49
  50. 50. Maximize parallel downloads Downloading 8 components in parallel using 4 hostnames 50
  51. 51. Yahoo! performance tests 51
  52. 52. Maximize parallel downloads Yahoo! performance guidelines: Use at least 2 hostnames Use no more than 4 hostnames Reduce number of components in page 2-4 domains give optimal performance - test! Remember: Javascripts are usually downloaded and parsed sequentially EXAMPLE: Panamera Family Tree - 1 vs 4 domains 52
  53. 53. Visual optimizations Progressive Enhancement + scripts at bottom can cause load flickering Example: Throttle checkbox plugin How do we prevent this? Hide using CSS until Javascript shows the enhanced component? Example: Test checkbox using disabled Javascript 53
  54. 54. Visual optimizations Break the rules! Let’s hide enhanced components in HEAD using Javascript. Load external stylesheet hideOnLoad.css using document.write() <script> document.write(‘<link href=”...”></link>’); </script> 54
  55. 55. Cache busting Add version numbers on external resources: Stylesheets Javascript files CSS sprites Images Example: <script src=”jquery.fi.checkbox.js?v=1.0” type=”...”></script> 55
  56. 56. Firefox Plugins Firebug plugin & Firebug lite Web Developer toolbar HTML Validator YSlow Page Speed PixelPerfect Example: atari.com SenSEO Example: panamera.com 500k visitors since Sep10. SEO is generating 10% of visitors - most popular path after user typing in URL 56
  57. 57. Tools Charles http proxy Bandwidth throttling Excellent request/response sniffing Record sessions Can parse binary AMF messages (Action Message Format) used by Adobe Flash Speed Tracer for Chrome IDE: Aptana Studio Based on Eclipse. Good support for JS frameworks! 57
  58. 58. Further reading Yahoo Performance http://developer.yahoo.com/performance/ A List Apart - http://alistapart.com Sitepoint - http://sitepoint.com Smashing Magazine - http://smashingmagazine.com Ajaxian - http://ajaxian.com/ John Resig’s Blog - http://ejohn.com Steve Souder’s Blog - http://stevesouders.com 58
  59. 59. Thanks! C Contact: david.lindkvist@f-i.com www.f-i.com 59

×