Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Javascript done right - Open Web Camp III

Dirk Ginader
September 26, 2011

Javascript done right - Open Web Camp III

There is no such thing as the one right way to write Javascript but there is an infinite number of opportunities to do it wrong. Dirk Ginader is showing Best Practices he's been using and constantly developing for many years at Yahoo: A comprehensive set of tips and tricks on how to write Javascript in a maintainable, understandable, accessible, internationalized, extendable and speedy way.

Dirk Ginader

September 26, 2011
Tweet

More Decks by Dirk Ginader

Other Decks in Technology

Transcript

  1. What is “good” Javascript? • From a User Perspective: –

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

    understandable – reusable – extensible – optimized – secure – internationalized – optional – accessible
  3. 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...
  4. 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.
  5. 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} */
  6. Understandable -> Documented • YUI Doc now even prettier thanks

    to Carlo & Dana: http://www.yuiblog.com/blog/ 2010/10/01/yuidoc-dana-theme/
  7. Understandable -> Structured • HTML – Markup • CSS –

    Design • Javascript – Interaction
  8. Understandable -> Structured • CSS for Javascript – <script> document.documentElement.className

    += ' js'; </script> <style> .module{ /* with JS */ } .js .module{ /* without JS */ } </style>
  9. 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/
  10. 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
  11. 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
  12. Reusable • You’re using and understand just one Javascript Framework?

    – learn Javascript! – look under the hood – understand Errors
  13. Reusable • Javascript Frameworks/Libraries help to – not reinvent the

    wheel all over again – keep Code fresh – secure quality – write modular applications rather than “scripts”
  14. Reusable •“Standing on the Shoulders of Giants” •“Zwerge auf den

    Schultern von Riesen” •“nanos gigantium humeris insidentes”
  15. Extensible •What is the most popular about jQuery? - THE

    PLUGINS! $.fn.extend({ accessibleTabs: function(config) { return this.each(function() { //... } } }); $(".tabs").accessibleTabs();
  16. 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!}
  17. Extensible •Extending something out there instead of writing it all

    over again •Being prepared for demands that are not yet known
  18. • 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
  19. 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
  20. 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', ... });
  21. Optimized for Performance • reduce “reflows” after every DOM-manipulation the

    Browser needs to rerender! • Changing CSS is usually faster than changing the DOM $('<style type="text/css"> a { color: red; } </ style>').appendTo('head');
  22. 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);
  23. Optimized for Performance • changing the DOM using: – innerHTML:

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

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

    el = document.getElementById('list'); li = []; li[0] = '<li>hallo 1</li>'; li[1] = '<li>hallo 2</li>'; li[2] = '<li>hallo 3</li>'; el.innerHTML = li.join(''); – even faster as also array.push is slow in IE...
  26. 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!
  27. 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...
  28. 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
  29. 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}
  30. 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
  31. 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" };
  32. 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! •...
  33. 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
  34. 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
  35. 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
  36. Accessible • WAI-ARIA – maps UI Elements that are well

    known on the Desktop to Elements in the Browser – teaches meaning to non-semantic markup
  37. Accessible • WAI-ARIA – proper realtime updates •Live Regions –

    real Form Validation state •aria-required="true" •aria-invalid="true" – real Dialogs •role="alert"
  38. thank you :-) • http://ginader.com • http://twitter.com/ginader • http://github.com/ginader/ •

    http://www.slideshare.net/ginader • http://speakerrate.com/speakers/ 225-ginader