Maintainable Javascript carsonified

Christian Heilmann
Christian HeilmannSenior Program Manager Developer Experience and Evangelism at Microsoft
Maintainable JavaScript




                                      Chris&an Heilmann
            Carsonfied online conference, September 2010
JavaScript is awesome!
Nowadays writing
JavaScript is
wonderfully easy.
Libraries patch the
support holes in
browsers.
Pure JavaScript
environments allow
us to really play
with the language.
JavaScript is dead
easy to learn and
the first steps are
already very
rewarding.
This is also the
problem of
JavaScript.
The web is not a
closed environment
where we can
dictate the
technologies people
use.
Some of the things I
will talk about
today will seem
outdated or overly
cautious.
The reason is that I
want to build a web
that works.
For far too long we
have built a mess
that barely
functions and is
hard to change.
So here are a few
ideas and concepts
you should follow if
you write
JavaScript.
★   Using, not abusing libraries
★   Separation of concerns
★   Building for extensibility
★   Documenting your work
★   Planning for performance
★   Avoiding double maintenance
★   Live code vs. development code
Libraries fix
browsers and make
the complex simple.
They make web
development
predictable.
Building without
libraries means
constant catch-up
with the browser
market.
Do not mix and
match libraries
though.
Stick with one and
use it to its
strengths.
If the library totally
re-invents JS as we
know it, this is fine.
But: writing in an
abstraction syntax
is not writing
JavaScript.
Quick two-liners do
not replace
architecting and
planning.
Professional
libraries come as a
pick and mix
solution.
Include what you
need and when you
need it - not the
kitchen sink
approach.
One big danger of
libraries is to tie the
markup and your
scripts far too close
to each other.
Small looking loops
can actually be very
slow.
Long CSS selectors
are dangerous.
Pick your plugins by
how well they are
documented, how
well supported and
how easy they are
to extend.
Not by how flashy
they are.
★   Using, not abusing libraries
★   Separation of concerns
★   Building for extensibility
★   Documenting your work
★   Planning for performance
★   Avoiding double maintenance
★   Live code vs. development code
This is old news.
Take each
technology on the
web and use it for
what it was meant
to.
HTML that works
without JavaScript
should not be aded
using JavaScript.
HTML that only
makes sense when
JavaScript is
available should be
added with
JavaScript.
Instructions that
describe
functionality that is
dependent on JS
should also be
added by it.
Text, classes and ID
names are very
much prone to
change.
So don’t spread
them all over your
scripts but keep
them in one place
for maintenance.
Public configuration
objects are a great
idea.
Most underused
element:
          <button>
Buttons by
definition are there
to trigger script
functionality - so
use them instead of
links.
Links should point
to a real resource -
a url, a server
endpoint or an
anchor.
Empty links, void(0)
# and other hacks
don’t make any
sense.
Styling should be
done in CSS, not in
your JavaScript.
Calculated positions
are of course the
exception to that
rule.
Adding and
removing classes
makes sure
designers have a
handle and you
don’t have to worry.
By adding a class to
a parent element
you can swiftly hide
a lot of elements
you’d otherwise
have to loop over.
Adding a “js” class
to the body means
CSS designers can
define two views
easily.
Make maintainers
not have to know JS
or change yours!
★   Using, not abusing libraries
★   Separation of concerns
★   Building for extensibility
★   Documenting your work
★   Planning for performance
★   Avoiding double maintenance
★   Live code vs. development code
Using libraries
means using a lot of
anonymous
functions.
Most of the time at
the end of a
massive chain of
methods or for
every click().
Naming and calling
these methods
makes more sense
as you create a
single space to
maintain.
Never think your
script is done and
you thought of all
use cases.
This is why we have
dozens of lightbox
plugins in jQuery all
doing almost the
same thing.
Instead of building
a “one size fits all”
solution, split it up
into small solutions
that do one thing
and allow for mixing
and matching.
Think about firing
off custom events at
interesting
moments.
This allows people
who want to extend
your solution to do
so without having
to touch the main
code.
Don’t limit anything
to a fixed size or
amount. Instead
make it a variable in
the configuration
object.
★   Using, not abusing libraries
★   Separation of concerns
★   Building for extensibility
★   Documenting your work
★   Planning for performance
★   Avoiding double maintenance
★   Live code vs. development code
Documentation is
what we rely on
when we get lost.
People think
documentation
replaces good code
examples.
The issue is that as
developers, we
almost never start
with the
documentation.
Instead we dive into
the code and mess
about with it.
We read the
documentation
when we get stuck.
Which is why code
comments and
descriptive variable
and function names
make your code
easy to maintain.
Comment the
special case, not the
obvious.
Keep function and
variable names
short and to the
point.
Your documentation
should explain
applying and
extending the code,
not the code itself.
Don’t worry about
the size of
comments - a good
process deals with
that.
GitHub and Google
Code is the new
View-Source, so add
value, not only
solutions.
★   Using, not abusing libraries
★   Separation of concerns
★   Building for extensibility
★   Documenting your work
★   Planning for performance
★   Avoiding double maintenance
★   Live code vs. development code
You can find a lot of
great performance
tricks on the web
when it comes to
JS.
Read those with the
use case in mind.
Tricks necessary to
make Google Mail
on mobiles run
smooth are edge
cases.
Performance is a
specialist topic and
can be handled a lot
in build processes.
If a performance
change means re-
educating a whole
team of developers
it is probably not
worth it.
Scripts can convert
and change code
written in a
predictable fashion.
Hacks and shortcuts
need to be fixed by
humans.
The performance of
JS itself is not really
the issue you should
be concentrating
on.
Slowness of the
DOM and reflow of
the interface is
where users get
hurt.
So use DOM access
sparingly.
Assemble HTML as
as string and use
innerHTML once
instead of adding to
it.
Use Event
Delegation instead
of hundreds of
event handlers.
Store information in
JS objects instead
of HTML attributes.
Make your code
easy to understand
and clean and add a
performance review
and refactoring step
at the end.
★   Using, not abusing libraries
★   Separation of concerns
★   Building for extensibility
★   Documenting your work
★   Planning for performance
★   Avoiding double maintenance
★   Live code vs. development code
Double
maintenance of
code is a bad idea.
Validation rules
might get out of
sync.
This is always the
killer argument of
enemies of
progressive
enhancement.
“I spend a lot of time doing
 form validation in JavaScript
 - why should I repeat the
 same on the server side?
                                 “
Because there is no
security in
JavaScript!
If all you do is
validate in JS,
attackers will have a
field day with your
server.
Besides, there is no
need to repeat
validation rules.
Maintainable Javascript carsonified
Maintainable Javascript carsonified
That way you
validate on the
server and you can
use the same rules
for your JS...
Maintainable Javascript carsonified
Form validation
scripts are
annoying.
You need to access
the right parts, read
and write from the
DOM, change styles
and and and...
You can leave it all
to the server and
still save your users
a full page reload.
Request type
switching is the
answer.
JavaScript libraries
add a special
footprint to the
server request when
calling content via
Ajax.
Maintainable Javascript carsonified
(so should your own
Ajax solutions, btw)
You can use this to
send content to
Ajax requests and
other content to
normal requests.
Maintainable Javascript carsonified
You can use this to
render a form
completely server
side and just send a
string back for each
request.
 http://github.com/codepo8/validationdemo
Maintainable Javascript carsonified
Filter inputs for
nasties and include
the rules.
If the form has not
been submitted,
include the form
code.
this is like /pattern/.test($(name).value)




        Otherwise loop through the
        rules and check the data
        that was sent against them.
If there was an error - show
the form again.
Otherwise say thanks.
The form itself is a
simple HTML form
doing all the
dynamic rendering
with PHP...
Maintainable Javascript carsonified
Check for the error array
and if there is an error,
show it.
Otherwise show a * to
indicate required field.
Check if the form was sent
via Ajax - if not, render the
form element.
If there was an error, say
so.
At the field show the error
or the * SPAN.
And all you then
need to do in
JavaScript is to
override the form
submission.
And instead replace
the innerHTML of
the form on every
submit.
An example using
YUI3...
On submission of the form
  load the validate.php file
  with the config and don’t
  send off the form.


Load the IO and Node
module.
Define the configuration
for the Ajax call.
If the Ajax call was a
success, replace the
innerHTML of the form with
the HTML returned from
validate.php
In addition to that, focus
on the first element with an
error message - this helps
with assistive technology.
If the Ajax call failed, send
the form.
Subscribe to the Ajax
events.
Writing lots of
HTML with
JavaScript is
painful.
So if you can avoid
it, avoid it :)
You can take this
concept further.
Make the backend
render HTML to use
with include() in
PHP and load the
same with Ajax.
http://isithackday.com/hacks/flickrcollector/
http://github.com/codepo8/flickrcollector
Using Node.js you
can move that later
on to a pure
JavaScript solution.
http://www.yuiblog.com/blog/2010/04/09/node-js-
yui-3-dom-manipulation-oh-my/
★   Using, not abusing libraries
★   Separation of concerns
★   Building for extensibility
★   Documenting your work
★   Planning for performance
★   Avoiding double maintenance
★   Live code vs. development code
Live code is not
development code.
If you really get to a
high traffic level
with your scripts
you should have a
build process.
A build process
should do a few
things for you.
★   Remove comments
★   Remove whitespace
★   Bundle lots of files into one
★   Pack the code
★   Version, add the author and
    date.
★   Validate + Lint
http://jslint.com/

http://blog.macromates.com/2007/javascript-tools/

http://closure-compiler.appspot.com/home

http://code.google.com/closure/compiler/docs/
gettingstarted_api.html

http://developer.yahoo.com/yui/compressor/

http://yuiblog.com/blog/2008/02/11/helping-the-yui-
compressor


                                    Tools
http://refresh-sf.com/yui/

http://www.ejeliot.com/blog/73
Some examples of
great practices in
the wild.
Give browsers what
they can do and use
what they do better!
Maintainable Javascript carsonified
Easing the use of
web fonts for better
typography.
http://code.google.com/webfonts/preview#font-family=Lobster
Simply adding a link
doesn’t give you
feedback though...
Using JS to load the
fonts on the other
hand does.
Maintainable Javascript carsonified
Classes added to the root element
by the Google WebFont loader

.wf-inactive
.wf-active
.wf-tangerine-n4-inactive
.wf-tangerine-n7-active
.wf-droidsans-n4-inactive
[...]

n4 - normal              i4 - italic
n7 - bold                i7 - bold italic
http://code.google.com/apis/webfonts/docs/webfont_loader.html
<style type="text/css">
 .wf-inactive p {
    font-family: serif;
    font-size:12px;
 }
 .wf-active p {
   font-family: 'Tangerine', serif;
   font-size:20px;
 }
 .wf-inactive h1 {
   font-family: serif;
   font-size: 16px
 }
 .wf-active h1 {
   font-family: 'Cantarell', serif;
   font-size: 35px
 }
</style>

http://code.google.com/apis/webfonts/docs/webfont_loader.html
WebFontConfig = {
 google: {
   families: [ 'Tangerine', 'Cantarell' ]
 },
 typekit: {
   id: 'myKitId'
 },
 loading: function() { },
 fontloading: function(family, info) {},
 fontactive: function(family, info) {},
 fontinactive: function(family, info) {},
 active: function() {},
 inactive: function() {}
};
And that’s that. A
lot about writing
maintainable
JavaScript is to
avoid writing it
yourself :)
Christian Heilmann
http://wait-till-i.com        Thanks!
http://developer-evangelism.com
http://twitter.com/codepo8
1 of 150

Recommended

Basics of node.js by
Basics of node.jsBasics of node.js
Basics of node.jsYasir Wani
2.9K views68 slides
Going native with html5 web components by
Going native with html5 web componentsGoing native with html5 web components
Going native with html5 web componentsJames York
628 views25 slides
Java script hello world by
Java script hello worldJava script hello world
Java script hello worldsanket kulkarni
152 views8 slides
Introduction to Java Scripting by
Introduction to Java ScriptingIntroduction to Java Scripting
Introduction to Java Scriptingfantasticdigitaltools
4.9K views43 slides
Javascript by
JavascriptJavascript
JavascriptSushma M
1.9K views49 slides
Java script basics for beginners by
Java script basics for beginners  Java script basics for beginners
Java script basics for beginners Ketan Raval
147 views17 slides

More Related Content

What's hot

Type script vs javascript come face to face in battleground by
Type script vs javascript come face to face in battlegroundType script vs javascript come face to face in battleground
Type script vs javascript come face to face in battlegroundKaty Slemon
65 views29 slides
file1 by
file1file1
file1Anurag Agarwal
511 views158 slides
Basics java scripts by
Basics java scriptsBasics java scripts
Basics java scriptsch samaram
2.2K views71 slides
Jscript part1 by
Jscript part1Jscript part1
Jscript part1Girish Srivastava
2.8K views54 slides
Java scripts by
Java scriptsJava scripts
Java scriptsCapgemini India
4.3K views45 slides
Understanding progressive enhancement - yuiconf2010 by
Understanding progressive enhancement - yuiconf2010Understanding progressive enhancement - yuiconf2010
Understanding progressive enhancement - yuiconf2010Christian Heilmann
6.6K views134 slides

What's hot(20)

Type script vs javascript come face to face in battleground by Katy Slemon
Type script vs javascript come face to face in battlegroundType script vs javascript come face to face in battleground
Type script vs javascript come face to face in battleground
Katy Slemon65 views
Basics java scripts by ch samaram
Basics java scriptsBasics java scripts
Basics java scripts
ch samaram2.2K views
Understanding progressive enhancement - yuiconf2010 by Christian Heilmann
Understanding progressive enhancement - yuiconf2010Understanding progressive enhancement - yuiconf2010
Understanding progressive enhancement - yuiconf2010
Christian Heilmann6.6K views
TDD with BDD in PHP and Symfony by Kamil Adryjanek
TDD with BDD in PHP and SymfonyTDD with BDD in PHP and Symfony
TDD with BDD in PHP and Symfony
Kamil Adryjanek5.3K views
Spring boot vs spring framework razor sharp web applications by Katy Slemon
Spring boot vs spring framework razor sharp web applicationsSpring boot vs spring framework razor sharp web applications
Spring boot vs spring framework razor sharp web applications
Katy Slemon79 views
Node.JS error handling best practices by Yoni Goldberg
Node.JS error handling best practicesNode.JS error handling best practices
Node.JS error handling best practices
Yoni Goldberg13.7K views
Ui Testing on Windows Phone by Stuart Lodge
Ui Testing on Windows PhoneUi Testing on Windows Phone
Ui Testing on Windows Phone
Stuart Lodge4.4K views
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development by Evan Mullins
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to DevelopmentWordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
Evan Mullins356 views
Learning to be IDE Free (PrDC 2015) by David Wesst
Learning to be IDE Free (PrDC 2015)Learning to be IDE Free (PrDC 2015)
Learning to be IDE Free (PrDC 2015)
David Wesst517 views
JavaScript Revolution - 5/Nov/13 - PrDC Saskatoon, SK by David Wesst
JavaScript Revolution - 5/Nov/13 - PrDC Saskatoon, SKJavaScript Revolution - 5/Nov/13 - PrDC Saskatoon, SK
JavaScript Revolution - 5/Nov/13 - PrDC Saskatoon, SK
David Wesst1.7K views

Similar to Maintainable Javascript carsonified

How backbone.js is different from ember.js? by
How backbone.js is different from ember.js?How backbone.js is different from ember.js?
How backbone.js is different from ember.js?SoftProdigy - We know software!
284 views8 slides
Ajax Performance by
Ajax PerformanceAjax Performance
Ajax Performancekaven yan
1.8K views56 slides
30 Skills to Master to Become a Senior Software Engineer by
30 Skills to Master to Become a Senior Software Engineer30 Skills to Master to Become a Senior Software Engineer
30 Skills to Master to Become a Senior Software EngineerSean Coates
775 views73 slides
Quo vadis, JavaScript? Devday.pl keynote by
Quo vadis, JavaScript? Devday.pl keynoteQuo vadis, JavaScript? Devday.pl keynote
Quo vadis, JavaScript? Devday.pl keynoteChristian Heilmann
4.1K views81 slides
C# and java comparing programming languages by
C# and java  comparing programming languagesC# and java  comparing programming languages
C# and java comparing programming languagesShishir Roy
658 views58 slides
Doing Modern Web, aka JavaScript and HTML5 in the Enterprise NYC Code Camp by
Doing Modern Web, aka JavaScript and HTML5 in the Enterprise NYC Code CampDoing Modern Web, aka JavaScript and HTML5 in the Enterprise NYC Code Camp
Doing Modern Web, aka JavaScript and HTML5 in the Enterprise NYC Code CampChris Love
1.9K views43 slides

Similar to Maintainable Javascript carsonified(20)

Ajax Performance by kaven yan
Ajax PerformanceAjax Performance
Ajax Performance
kaven yan1.8K views
30 Skills to Master to Become a Senior Software Engineer by Sean Coates
30 Skills to Master to Become a Senior Software Engineer30 Skills to Master to Become a Senior Software Engineer
30 Skills to Master to Become a Senior Software Engineer
Sean Coates775 views
C# and java comparing programming languages by Shishir Roy
C# and java  comparing programming languagesC# and java  comparing programming languages
C# and java comparing programming languages
Shishir Roy658 views
Doing Modern Web, aka JavaScript and HTML5 in the Enterprise NYC Code Camp by Chris Love
Doing Modern Web, aka JavaScript and HTML5 in the Enterprise NYC Code CampDoing Modern Web, aka JavaScript and HTML5 in the Enterprise NYC Code Camp
Doing Modern Web, aka JavaScript and HTML5 in the Enterprise NYC Code Camp
Chris Love1.9K views
You should Know, What are the Common mistakes a node js developer makes? by Surendra kumar
You should Know, What are the Common mistakes a node js developer makes?You should Know, What are the Common mistakes a node js developer makes?
You should Know, What are the Common mistakes a node js developer makes?
Surendra kumar55 views
Five Common Angular Mistakes by Backand Cohen
Five Common Angular MistakesFive Common Angular Mistakes
Five Common Angular Mistakes
Backand Cohen560 views
Isomorphic JavaScript: #DevBeat Master Class by Spike Brehm
Isomorphic JavaScript: #DevBeat Master ClassIsomorphic JavaScript: #DevBeat Master Class
Isomorphic JavaScript: #DevBeat Master Class
Spike Brehm24.1K views
Workshop - The Little Pattern That Could.pdf by TobiasGoeschel
Workshop - The Little Pattern That Could.pdfWorkshop - The Little Pattern That Could.pdf
Workshop - The Little Pattern That Could.pdf
TobiasGoeschel120 views
Flu3nt highlights by dswork
Flu3nt highlightsFlu3nt highlights
Flu3nt highlights
dswork2.4K views
Create first android app with MVVM Architecture by khushbu thakker
Create first android app with MVVM ArchitectureCreate first android app with MVVM Architecture
Create first android app with MVVM Architecture
khushbu thakker182 views
Intro to mobile web application development by zonathen
Intro to mobile web application developmentIntro to mobile web application development
Intro to mobile web application development
zonathen1.3K views
learn mvc project in 7 day by Quach Long
learn mvc project in 7 daylearn mvc project in 7 day
learn mvc project in 7 day
Quach Long2.4K views

More from Christian Heilmann

Develop, Debug, Learn? - Dotjs2019 by
Develop, Debug, Learn? - Dotjs2019Develop, Debug, Learn? - Dotjs2019
Develop, Debug, Learn? - Dotjs2019Christian Heilmann
1.1K views55 slides
Hinting at a better web by
Hinting at a better webHinting at a better web
Hinting at a better webChristian Heilmann
2.8K views33 slides
Taking the "vile" out of privilege by
Taking the "vile" out of privilegeTaking the "vile" out of privilege
Taking the "vile" out of privilegeChristian Heilmann
1K views64 slides
Seven ways to be a happier JavaScript developer - NDC Oslo by
Seven ways to be a happier JavaScript developer - NDC OsloSeven ways to be a happier JavaScript developer - NDC Oslo
Seven ways to be a happier JavaScript developer - NDC OsloChristian Heilmann
1.5K views52 slides
Artificial intelligence for humans… #AIDC2018 keynote by
Artificial intelligence for humans… #AIDC2018 keynoteArtificial intelligence for humans… #AIDC2018 keynote
Artificial intelligence for humans… #AIDC2018 keynoteChristian Heilmann
1.2K views56 slides
Killing the golden calf of coding - We are Developers keynote by
Killing the golden calf of coding - We are Developers keynoteKilling the golden calf of coding - We are Developers keynote
Killing the golden calf of coding - We are Developers keynoteChristian Heilmann
3.1K views35 slides

More from Christian Heilmann(20)

Seven ways to be a happier JavaScript developer - NDC Oslo by Christian Heilmann
Seven ways to be a happier JavaScript developer - NDC OsloSeven ways to be a happier JavaScript developer - NDC Oslo
Seven ways to be a happier JavaScript developer - NDC Oslo
Christian Heilmann1.5K views
Artificial intelligence for humans… #AIDC2018 keynote by Christian Heilmann
Artificial intelligence for humans… #AIDC2018 keynoteArtificial intelligence for humans… #AIDC2018 keynote
Artificial intelligence for humans… #AIDC2018 keynote
Christian Heilmann1.2K views
Killing the golden calf of coding - We are Developers keynote by Christian Heilmann
Killing the golden calf of coding - We are Developers keynoteKilling the golden calf of coding - We are Developers keynote
Killing the golden calf of coding - We are Developers keynote
Christian Heilmann3.1K views
Five ways to be a happier JavaScript developer by Christian Heilmann
Five ways to be a happier JavaScript developerFive ways to be a happier JavaScript developer
Five ways to be a happier JavaScript developer
Christian Heilmann859 views
Progressive Web Apps - Covering the best of both worlds - DevReach by Christian Heilmann
Progressive Web Apps - Covering the best of both worlds - DevReachProgressive Web Apps - Covering the best of both worlds - DevReach
Progressive Web Apps - Covering the best of both worlds - DevReach
Christian Heilmann956 views
Progressive Web Apps - Covering the best of both worlds by Christian Heilmann
Progressive Web Apps - Covering the best of both worldsProgressive Web Apps - Covering the best of both worlds
Progressive Web Apps - Covering the best of both worlds
Christian Heilmann799 views
Non-trivial pursuits: Learning machines and forgetful humans by Christian Heilmann
Non-trivial pursuits: Learning machines and forgetful humansNon-trivial pursuits: Learning machines and forgetful humans
Non-trivial pursuits: Learning machines and forgetful humans
Christian Heilmann531 views
Progressive Web Apps - Bringing the web front and center by Christian Heilmann
Progressive Web Apps - Bringing the web front and center Progressive Web Apps - Bringing the web front and center
Progressive Web Apps - Bringing the web front and center
Christian Heilmann1.2K views
The Soul in The Machine - Developing for Humans (FrankenJS edition) by Christian Heilmann
The Soul in The Machine - Developing for Humans (FrankenJS edition)The Soul in The Machine - Developing for Humans (FrankenJS edition)
The Soul in The Machine - Developing for Humans (FrankenJS edition)
Christian Heilmann917 views

Maintainable Javascript carsonified