Slide 1

Slide 1 text

Dirk Ginader | Yahoo! Inc. Javascript done right @ginader

Slide 2

Slide 2 text

What is “good” Javascript? • From a User Perspective?

Slide 3

Slide 3 text

What is “good” Javascript? • From a User Perspective: – THEY DON’T CARE!* *as long as it works...

Slide 4

Slide 4 text

What is “good” Javascript? • From a Developer Perspective?

Slide 5

Slide 5 text

What is “good” Javascript? • From a Developer Perspective: – understandable – reusable – extensible – optimized – secure – internationalized – optional – accessible

Slide 6

Slide 6 text

Understandable • don’t be “too clever”

Slide 7

Slide 7 text

Understandable • don’t be “too clever”

Slide 8

Slide 8 text

Understandable • not everybody understands: – Ternary: • var d = (x < m) ? 'l' : 'r';

Slide 9

Slide 9 text

Understandable • not everybody understands: – Regex: • ^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za- z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@ ((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$

Slide 10

Slide 10 text

Understandable • not everybody understands: – Shakespeare: • /(bb|[^b]{2})/

Slide 11

Slide 11 text

Understandable • If there’s no good way around cleverness then: – good naming – documentation

Slide 12

Slide 12 text

for more WTF check • http://wtfjs.com

Slide 13

Slide 13 text

Understandable -> Documented • Writing Docs isn’t fun • Reading Code you wrote 5 years ago and didn’t document is worse... • Reading undocumented code someone else wrote even more so...

Slide 14

Slide 14 text

Understandable -> Documented • use clear variable and function names: – a = b(c) // Whut? – user = getUserOfProduct(productId) // Alright! • good comments – // IE seems to break here... – // dirty hack. This must never go live! – // this works. No idea why. Better don’t touch.

Slide 15

Slide 15 text

Understandable -> Documented • exceptionally good comments: – YUI Doc: http://developer.yahoo.com/ yui/yuidoc/ – creates the YUI API Dos automatically – simple Javadoc syntax /** * short description * @method methodName * @param {bool} * @returm {type} */

Slide 16

Slide 16 text

Understandable -> Documented • YUI Doc now even prettier thanks to Carlo & Dana: http://www.yuiblog.com/blog/ 2010/10/01/yuidoc-dana-theme/

Slide 17

Slide 17 text

Understandable -> Structured • HTML – Markup • CSS – Design • Javascript – Interaction

Slide 18

Slide 18 text

Understandable -> Structured • CSS for Javascript – document.documentElement.className += ' js'; .module{ /* with JS */ } .js .module{ /* without JS */ }

Slide 19

Slide 19 text

Understandable -> Structured • HTML for Javascript – Mustache Templating Partials for Ajax content – /partials/login_success.html – Hello {{user_name}} You have sucesfully registered Your currently have {{user_points}} points – { user_name : “dude”, user_points : 123 } – http://mustache.github.com/

Slide 20

Slide 20 text

Reusable • find patterns • largest common denominator • when you’re writing a new dropdown menu every month something is very wrong... • write ONE dropdown menu and keep making it better

Slide 21

Slide 21 text

Reusable • open source != “I’m giving it away for free” • open source == “I get free testers, co-developers, fame and fortune” • github is full of excellent code • “FORK OFF” - make it better! • a plugin for an existing library is a great start

Slide 22

Slide 22 text

Reusable • How do you write Javascript? – jQuery, YUI and alike? – all “pure”?

Slide 23

Slide 23 text

Reusable • You’re using and understand just one Javascript Framework? – learn Javascript! – look under the hood – understand Errors

Slide 24

Slide 24 text

Reusable • You don’t use Frameworks? – you should!

Slide 25

Slide 25 text

Reusable • Javascript Frameworks/Libraries help to – not reinvent the wheel all over again – keep Code fresh – secure quality – write modular applications rather than “scripts”

Slide 26

Slide 26 text

Reusable •“Standing on the Shoulders of Giants” •“Zwerge auf den Schultern von Riesen” •“nanos gigantium humeris insidentes”

Slide 27

Slide 27 text

Extensible •What is the most popular about jQuery? - THE PLUGINS! $.fn.extend({ accessibleTabs: function(config) { return this.each(function() { //... } } }); $(".tabs").accessibleTabs();

Slide 28

Slide 28 text

Extensible •Everything can have plugins! •Tiny Form Validation script: addValidator : function(name,func){ this.validators[name] = func; } this.addValidator('isText',function(el){ var filter = /^[a-zA-Z\ ]+$/; return filter.test(el.get('value')); }); if( !this.validators['isText'](el) ){ //error!}

Slide 29

Slide 29 text

Extensible •Extending something out there instead of writing it all over again •Being prepared for demands that are not yet known

Slide 30

Slide 30 text

• Good Development Code != good Production Code • Good for Development: – granular code split over many files •module / config / i18n / init / etc – many comments – examples Optimized for Development

Slide 31

Slide 31 text

Optimized for Production • Good Development Code != good Production Code • Good for Production: – code combined into as few files as possible – comments and whitespace removed – optional code-minification

Slide 32

Slide 32 text

Optimized for Production • YUI Compressor http://developer.yahoo.com/yui/ compressor/ • Google Closure Compiler http://code.google.com/closure/ compiler/

Slide 33

Slide 33 text

Optimized for Performance • Caching of DOM-accesses var el = document.getElementById('bla'); • CSS is MUCH faster than JS when it’s about changing the DOM el.addClass('bla'); instead of el.css({ width:'20px', height:'20px', ... });

Slide 34

Slide 34 text

Optimized for Performance • reduce “reflows” after every DOM-manipulation the Browser needs to rerender! • Changing CSS is usually faster than changing the DOM $(' a { color: red; } </ style>').appendTo('head');

Slide 35

Slide 35 text

Optimized for Performance • changing the DOM using: – classic DOM Methods: el = document.getElementById('list'); l1 = document.createElement('li'); t1 = document.createTextNode('hello 1'); l2 = document.createElement('li'); t2 = document.createTextNode('hello 2'); l3 = document.createElement('li'); t3 = document.createTextNode('hello 3'); l1.appendChild(t1); l2.appendChild(t2); l3.appendChild(t3); el.appendChild(t1).appendChild(t2).appendChild(t3);

Slide 36

Slide 36 text

Optimized for Performance • changing the DOM using: – innerHTML: el = document.getElementById('list'); li = '
  • hallo 1
  • '; li += '
  • hallo 2
  • '; li += '
  • hallo 3
  • '; el.innerHTML = li; – faster than DOM-Methods (thanks to IE)

    Slide 37

    Slide 37 text

    Optimized for Performance • changing the DOM using: – innerHTML: el = document.getElementById('list'); li = []; li.push('
  • hallo 1
  • '); li.push('
  • hallo 2
  • '); li.push('
  • hallo 3
  • '); el.innerHTML = li.join(''); – even faster because string concatenation in IE is slow

    Slide 38

    Slide 38 text

    Optimized for Performance • changing the DOM using: – innerHTML: el = document.getElementById('list'); li = []; li[0] = '
  • hallo 1
  • '; li[1] = '
  • hallo 2
  • '; li[2] = '
  • hallo 3
  • '; el.innerHTML = li.join(''); – even faster as also array.push is slow in IE...

    Slide 39

    Slide 39 text

    Optimized for Performance • changing the DOM using: – DOM Fragment: l = document.getElementById('list'); f = document.createDocumentFragment(); l1 = document.createElement('li'); t1 = document.createTextNode('hallo 1'); ... l1.appendChild(t1); l2.appendChild(t2); l3.appendChild(t3); f.appendChild(l1).appendChild(l2).appendChild(l3); el.appendChild(f); – Even faster! Just 1 DOM access!

    Slide 40

    Slide 40 text

    Secure • XSS is a massive security issue • never echo user inputs • filter inputs! whitelisting not blacklisting • define data types • trust nothing and nobody • be paranoid...

    Slide 41

    Slide 41 text

    Secure • Caja http://en.wikipedia.org/wiki/ Caja_project • “virtual iFrames” • no direct access to native objects • Transpiler on the Server • YUI3 1st Javascript Library being compatible

    Slide 42

    Slide 42 text

    International/Multilingual • UTF-8 • RTL/Bidi • If possible reuse strings that are in the HTML already • Use standards – Text {0} more text {1} yet more text {2} Text {0:currency} more text {1:symbol} even more text {2:amount} // {variable:comment}

    Slide 43

    Slide 43 text

    International/Multilingual • Variable sentence structure requires multi step translation – T_WELCOME : { en_US:”We welcome {0:user}” de_DE:”Wir heissen {0:user} willkommen” } – getText(‘de_DE’,‘T_WELCOME’,{user:”Dude”}) • check ISO Standards • HTML in Strings isn’t ideal but better than pseudo code • bold = asian symbols unreadable

    Slide 44

    Slide 44 text

    International/Multilingual TRANSLATIONS = { // check http://internationalisationtips.com ! O: "{market} open", ! OT: "{market} open in {timePeriod}", ! OE: "{market} open early", ! OET: "{market} open early in {timePeriod}", ! OER: "{market} open early for {reason}", ! OERT: "{market} open early for {reason} in {timePeriod}", ! OL: "{market} open late", ! OLT: "{market} open late in {timePeriod}", ! OLR: "{market} open late for {reason}", ! OLRT: "{market} open late for {reason} in {timePeriod}", ! C: "{market} close", ! CT: "{market} close in {timePeriod}", ! CE: "{market} close early", ! CET: "{market} close early in {timePeriod}", ! CER: "{market} close early for {reason}", ! CERT: "{market} close early for {reason} in {timePeriod}", ! CL: "{market} close late", ! CLT: "{market} close late in {timePeriod}", ! CLR: "{market} close late for {reason}", ! CLRT: "{market} close late for {reason} in {timePeriod}", ! X: "{market} closed" };

    Slide 45

    Slide 45 text

    Optional • Progressive Enhancement – Base functionality of the site needs to be available even though the user agent does not understand Javascript – Mobile != iPhone (Opera Mini is No.1!) •Search Machines •Paranoid Sysadmins •Y! has ~1% non-js Users -> Millions! •...

    Slide 46

    Slide 46 text

    Optional • base page has interaction thanks to: – Links – Forms – (+ everything important is visible!) • With Javascript: – Links that update the page become Buttons – Forms are being processed instantly – Infos can be hidden and shown

    Slide 47

    Slide 47 text

    Accessible • Tab order is super important • using focus() we can direct the user • tabindex=-1 makes everything focusable (for Javascript) • Ajax works but mind the load time • update Virtual Buffer

    Slide 48

    Slide 48 text

    Accessible • some Effects can make the JS Version more accessible – yellow fade to temporary highlight what changed – animated open close is easier to understand than a hard show/hide

    Slide 49

    Slide 49 text

    Accessible • WAI-ARIA – maps UI Elements that are well known on the Desktop to Elements in the Browser – teaches meaning to non-semantic markup

    Slide 50

    Slide 50 text

    Accessible • WAI-ARIA – proper realtime updates •Live Regions – real Form Validation state •aria-required="true" •aria-invalid="true" – real Dialogs •role="alert"

    Slide 51

    Slide 51 text

    No content

    Slide 52

    Slide 52 text

    thank you :-) • http://ginader.com • http://twitter.com/ginader • http://github.com/ginader/ • http://www.slideshare.net/ginader • http://speakerrate.com/speakers/ 225-ginader