Share
Embed
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
Transcript
52 slides
-
What is “good” Javascript? • From a User Perspective: –
THEY DON’T CARE!* *as long as it works... -
What is “good” Javascript? • From a Developer Perspective: –
understandable – reusable – extensible – optimized – secure – internationalized – optional – accessible -
Understandable • not everybody understands: – Ternary: • var d
= (x < m) ? 'l' : 'r'; -
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}$ -
Understandable • If there’s no good way around cleverness then:
– good naming – documentation -
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... -
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. -
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} */ -
Understandable -> Documented • YUI Doc now even prettier thanks
to Carlo & Dana: http://www.yuiblog.com/blog/ 2010/10/01/yuidoc-dana-theme/ -
Understandable -> Structured • HTML – Markup • CSS –
Design • Javascript – Interaction -
Understandable -> Structured • CSS for Javascript – <script> document.documentElement.className
+= ' js'; </script> <style> .module{ /* with JS */ } .js .module{ /* without JS */ } </style> -
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/ -
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 -
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 -
Reusable • How do you write Javascript? – jQuery, YUI
and alike? – all “pure”? -
Reusable • You’re using and understand just one Javascript Framework?
– learn Javascript! – look under the hood – understand Errors -
Reusable • Javascript Frameworks/Libraries help to – not reinvent the
wheel all over again – keep Code fresh – secure quality – write modular applications rather than “scripts” -
Reusable •“Standing on the Shoulders of Giants” •“Zwerge auf den
Schultern von Riesen” •“nanos gigantium humeris insidentes” -
Extensible •What is the most popular about jQuery? - THE
PLUGINS! $.fn.extend({ accessibleTabs: function(config) { return this.each(function() { //... } } }); $(".tabs").accessibleTabs(); -
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!} -
Extensible •Extending something out there instead of writing it all
over again •Being prepared for demands that are not yet known -
• 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 -
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 -
Optimized for Production • YUI Compressor http://developer.yahoo.com/yui/ compressor/ • Google
Closure Compiler http://code.google.com/closure/ compiler/ -
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', ... }); -
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'); -
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); -
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) -
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 -
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... -
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! -
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... -
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 -
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} -
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 -
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" }; -
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! •... -
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 -
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 -
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 -
Accessible • WAI-ARIA – maps UI Elements that are well
known on the Desktop to Elements in the Browser – teaches meaning to non-semantic markup -
Accessible • WAI-ARIA – proper realtime updates •Live Regions –
real Form Validation state •aria-required="true" •aria-invalid="true" – real Dialogs •role="alert" -
thank you :-) • http://ginader.com • http://twitter.com/ginader • http://github.com/ginader/ •
http://www.slideshare.net/ginader • http://speakerrate.com/speakers/ 225-ginader