HTML / CSS / JS
Best practices and optimization techniques
Fi (Fantasy Interactive)




     www.f-i.com       david.lindkvist@f-i.com


                                             2
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
Agenda
 HTML

 CSS

 Javascript & jQuery

 Performance optimizations

 Visual optimizations



                             4
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
GIF compression
 Each number represents a unique color
 GIF compress horizontally, thus an image like this will
 not compress well:




                                                      22
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
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
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
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
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
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
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
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
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
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
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
Example plugin pattern
 Template example: The Fi plugin pattern

 Real world example: The Fi checkbox plugin




                                              34
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
Qunit
 Latest version does not rely on jQuery

 Example: checkbox plugin unit test

 Testswarm.com




                                          36
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
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
Javascript files always block!
 Blocks render because they might document.write()

 Downloads sequentially




                                                     39
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
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
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
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
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
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
How do we reduce number of
HTTP requests?
 Merge common files
   Global Javascript files
   Global stylesheets


 Use CSS image sprites!




                             46
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
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
Maximize parallel downloads
 Downloading 2 components in parallel using 1
 hostname




                                                49
Maximize parallel downloads
 Downloading 8 components in parallel using 4
 hostnames




                                                50
Yahoo! performance tests




                           51
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
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
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
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
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
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
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
Thanks!




 C


     Contact: david.lindkvist@f-i.com   www.f-i.com



                                                      59

More Related Content

PPT
JavaScript & Dom Manipulation
PPTX
jQuery PPT
PPTX
Css position
PPT
Introduction to Cascading Style Sheets (CSS)
PDF
Introduction to HTML5
PDF
CSS3, Media Queries, and Responsive Design
PPTX
Lab #2: Introduction to Javascript
ODP
CSS Basics
JavaScript & Dom Manipulation
jQuery PPT
Css position
Introduction to Cascading Style Sheets (CSS)
Introduction to HTML5
CSS3, Media Queries, and Responsive Design
Lab #2: Introduction to Javascript
CSS Basics

What's hot (20)

PDF
jQuery for beginners
PPT
Introduction to JavaScript
PDF
Bootstrap
PPSX
Javascript variables and datatypes
PDF
Javascript basics
PPTX
PDF
CSS Day: CSS Grid Layout
PPT
Introduction to JavaScript (1).ppt
PDF
Introduction to HTML and CSS
PPT
Javascript
PPTX
HTML, CSS And JAVASCRIPT!
PPTX
JavaScript Basic
PDF
Html for beginners
PDF
Web Development Presentation
PPTX
Introduction to React JS for beginners
PDF
JavaScript - Chapter 12 - Document Object Model
PPTX
jQuery
PPTX
Html, CSS & Web Designing
PPT
Java Script ppt
jQuery for beginners
Introduction to JavaScript
Bootstrap
Javascript variables and datatypes
Javascript basics
CSS Day: CSS Grid Layout
Introduction to JavaScript (1).ppt
Introduction to HTML and CSS
Javascript
HTML, CSS And JAVASCRIPT!
JavaScript Basic
Html for beginners
Web Development Presentation
Introduction to React JS for beginners
JavaScript - Chapter 12 - Document Object Model
jQuery
Html, CSS & Web Designing
Java Script ppt
Ad

Viewers also liked (20)

ODP
Introduction of Html/css/js
PDF
Html / CSS Presentation
PPT
Html JavaScript and CSS
PPTX
An Overview of HTML, CSS & Java Script
PDF
reveal.js 3.0.0
PPTX
HTML5 Bootcamp: Essential HTML, CSS, & JavaScript
PPT
Web Development using HTML & CSS
PPT
JavaScript - An Introduction
PDF
HTML CSS JavaScript jQuery Training
PDF
An Seo’s Intro to Web Dev, HTML, CSS and JavaScript
PDF
Modular HTML, CSS, & JS Workshop
PPTX
Introduction to HTML and CSS
PPTX
Javascript
PPT
Introduction to CSS
PPT
Javascript
PPTX
HTML, CSS and Java Scripts Basics
PPT
Html Ppt
PPT
Php Presentation
PPT
8th Computer Jeopardy Game
PDF
Mobile development in age of Internet of Things and programming Apple Watch
Introduction of Html/css/js
Html / CSS Presentation
Html JavaScript and CSS
An Overview of HTML, CSS & Java Script
reveal.js 3.0.0
HTML5 Bootcamp: Essential HTML, CSS, & JavaScript
Web Development using HTML & CSS
JavaScript - An Introduction
HTML CSS JavaScript jQuery Training
An Seo’s Intro to Web Dev, HTML, CSS and JavaScript
Modular HTML, CSS, & JS Workshop
Introduction to HTML and CSS
Javascript
Introduction to CSS
Javascript
HTML, CSS and Java Scripts Basics
Html Ppt
Php Presentation
8th Computer Jeopardy Game
Mobile development in age of Internet of Things and programming Apple Watch
Ad

Similar to HTML CSS & Javascript (20)

PDF
Design Fast Websites
PDF
Adobe MAX 2008: HTML/CSS + Fireworks
PPT
Html & CSS - Best practices 2-hour-workshop
KEY
The Fast And The Fabulous
PDF
CSS Systems
KEY
Object Oriented CSS
PDF
Finding harmony in web development
PPTX
4087 chapter 08 8ed part2
PDF
Effective and Efficient Design with CSS3
PDF
Developer Pitfalls & Strategies for Improving Mobile Web Developer Experience
PDF
Advanced CSS Troubleshooting
PDF
CSS3: Ripe and Ready
PPTX
UI Principles Behind Design Thinking
ODP
Design Best Practices for WordPress
PDF
CSS3: Ripe and Ready to Respond
KEY
Artdm171 Week6 Images
PDF
Simply Responsive CSS3
PDF
Intro to CSS3
PDF
Advanced CSS Troubleshooting
PDF
Advanced CSS Troubleshooting & Efficiency
Design Fast Websites
Adobe MAX 2008: HTML/CSS + Fireworks
Html & CSS - Best practices 2-hour-workshop
The Fast And The Fabulous
CSS Systems
Object Oriented CSS
Finding harmony in web development
4087 chapter 08 8ed part2
Effective and Efficient Design with CSS3
Developer Pitfalls & Strategies for Improving Mobile Web Developer Experience
Advanced CSS Troubleshooting
CSS3: Ripe and Ready
UI Principles Behind Design Thinking
Design Best Practices for WordPress
CSS3: Ripe and Ready to Respond
Artdm171 Week6 Images
Simply Responsive CSS3
Intro to CSS3
Advanced CSS Troubleshooting
Advanced CSS Troubleshooting & Efficiency

Recently uploaded (20)

PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
DOCX
search engine optimization ppt fir known well about this
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Five Habits of High-Impact Board Members
PDF
A review of recent deep learning applications in wood surface defect identifi...
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
Hybrid model detection and classification of lung cancer
PDF
Unlock new opportunities with location data.pdf
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
Architecture types and enterprise applications.pdf
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PPT
Geologic Time for studying geology for geologist
PPT
Module 1.ppt Iot fundamentals and Architecture
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
A novel scalable deep ensemble learning framework for big data classification...
PPTX
Chapter 5: Probability Theory and Statistics
PPTX
observCloud-Native Containerability and monitoring.pptx
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PPTX
Modernising the Digital Integration Hub
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
search engine optimization ppt fir known well about this
sustainability-14-14877-v2.pddhzftheheeeee
Group 1 Presentation -Planning and Decision Making .pptx
Five Habits of High-Impact Board Members
A review of recent deep learning applications in wood surface defect identifi...
Enhancing emotion recognition model for a student engagement use case through...
Hybrid model detection and classification of lung cancer
Unlock new opportunities with location data.pdf
DP Operators-handbook-extract for the Mautical Institute
Architecture types and enterprise applications.pdf
O2C Customer Invoices to Receipt V15A.pptx
Geologic Time for studying geology for geologist
Module 1.ppt Iot fundamentals and Architecture
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
A novel scalable deep ensemble learning framework for big data classification...
Chapter 5: Probability Theory and Statistics
observCloud-Native Containerability and monitoring.pptx
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
Modernising the Digital Integration Hub

HTML CSS & Javascript

  • 1. HTML / CSS / JS Best practices and optimization techniques
  • 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. Agenda HTML CSS Javascript & jQuery Performance optimizations Visual optimizations 4
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. GIF compression Each number represents a unique color GIF compress horizontally, thus an image like this will not compress well: 22
  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Example plugin pattern Template example: The Fi plugin pattern Real world example: The Fi checkbox plugin 34
  • 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. Qunit Latest version does not rely on jQuery Example: checkbox plugin unit test Testswarm.com 36
  • 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. 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. Javascript files always block! Blocks render because they might document.write() Downloads sequentially 39
  • 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. 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. 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. 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. 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. 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. How do we reduce number of HTTP requests? Merge common files Global Javascript files Global stylesheets Use CSS image sprites! 46
  • 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. 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. Maximize parallel downloads Downloading 2 components in parallel using 1 hostname 49
  • 50. Maximize parallel downloads Downloading 8 components in parallel using 4 hostnames 50
  • 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. 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. 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. 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. 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. 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. 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. Thanks! C Contact: [email protected] www.f-i.com 59