Vitamin - Nourishment to Help the Web Grow

Features

Features > Dev Features > JavaScript

JavaScript is hip again; there’s no doubt about it. But if you’re starting to get down and dirty with it, there’s no excuse not to keep it clean.

Forums and mailing lists are full of requests about Ajax, DOM Scripting and how to use this or that library or effect. There is also an extraordinary amount of scripts, libraries and effects being developed and showcased, and the blogs and news sites specialising in scripting hardly have time to look at the demos properly before they are on Digg.com or del.icio.us and making the rounds from these sites.
Times to celebrate for those who have hung on to their skills when the DHTML craze subsided in 2001 and JavaScript became persona non grata on your CV as a main skill.

Code that shows love to the visitor

On the whole scripts released today are a lot cleaner than those of the DHTML era - most probably because of the lack of code forking necessary with browsers these days. I am also very pleased to see that the idea of Unobtrusive JavaScript has become quite common and is regarded as a goal for aspiring developers rather than a necessary evil.
One exception might be Ajax frameworks and code generators that spit out JavaScript - which lead some ‘JavaScript evangelists’ such as Jeremy Keith to coin new terms such as HIJAX - which in essence is Ajax with progressive enhancement instead of JavaScript dependencies.
All in all, it is a great time to be in the know and enthusiastic about JavaScript. Some behaviour patterns from the old days repeat themselves though. You see a lot of code that is ‘experimental’ and ‘not fit for a live system’ getting hyped and re-used without caring about the initial concerns of the developer - sometimes even blatantly omitting these warnings when reporting about the code experiment.
You also see the old chestnut of recoding visual effects that were pretty useless in older technologies with newer technologies. An image reflected in an animated lake is a two second ‘wow’ effect and from there on a nuisance, no matter if you achieve it using Java, Flash or JavaScript.

10 PRINT ‘HELLO MAINTAINER: GOTO HELL

So we’re making life a lot easier for the visitors coming to web sites by creating scripts that are not in their way, but only help then when and if their agents support it. On the other hand, as a maintainer a lot of code flung in my direction is a pain to sift through, debug and generally find the spots where I can customise or change settings. Call me Captain Obvious to the Rescue, but isn’t it time we - knowing very well that implementing and maintaining code is annoying and causes a lot of frustration - cut future maintainers of our code the same slack?
Unobtrusive JavaScript that is easy to maintain sounds like a winner that could help us spend less time with frustrating trial and error and give us some spare time we could spend on innovating or documenting what we do.

Maintainable JavaScript? But how?

So here’s an eight step plan to show you what can be done to make your scripts easier for the maintainer. Yes, some of the steps may be very obvious to the jet-set, well travelled and seasoned JavaScript developer, but it can’t hurt to remind ourselves of their virtues.
Furthermore, I dare any one of you to look at some older code and test it against them - I am not ashamed to admit that at times I looked at code and uttered expletives about the person responsible, only to find out later on that it was in fact me a few months back. Scope and feature changes together with looming deadlines and budget cuts breed bad code; it is a fact of software development.

Step 1: Keep Your Syntax and Structure Clean and Logical

This means you indent your code, keep a line-length limit of say 80 characters and keep functions reasonably small. A rule of thumb is to keep each task in its own function rather than having one large function to do everything. As an additional benefit, this means that you can re-use these functions when you extend the script at a later stage. Don’t go the ‘IDE generated - Java’ route though and create many many many one line functions - this can become more confusing than using one massive function.

There is a holy war going on about tabs vs. spaces for indenting and curly braces on an own line or on the same of the opening command. I don’t care, as long as you keep it consistent, and also consistent with the other code, were you to extend an already existing project. As an example let’s take a function that generates ‘close’ and ‘print’ links for a popup - links that only make sense when JavaScript is available and should therefore be generated with JavaScript.


function toolLinks(){
  var tools = document.createElement('ul');
  var item = document.createElement('li');
  var itemlink = document.createElement('a');
  itemlink.setAttribute('href', '#');
  itemlink.appendChild(document.createTextNode('close'));
  itemlink.onclick = function(){window.close();}
  item.appendChild(itemlink);
  tools.appendChild(item);
  var item2 = document.createElement('li');
  var itemlink2 = document.createElement('a');
  itemlink2.setAttribute('href', '#');
  itemlink2.appendChild(document.createTextNode('print'));
  itemlink2.onclick = function(){window.print();}
  item2.appendChild(itemlink2);
  tools.appendChild(item2);
  document.body.appendChild(tools);
}

You can make this a lot more readable by indenting and separating each task out into own functions:


function toolLinks(){
  var tools = document.createElement('ul');
  var item = document.createElement('li');
  var itemlink = createLink('#', 'close', closeWindow);
  item.appendChild(itemlink);
  tools.appendChild(item);
  var item2 = document.createElement('li');
  var itemlink2 = createLink('#', 'print', printWindow);
  item2.appendChild(itemlink2);
  tools.appendChild(item2);
  document.body.appendChild(tools);
}
function printWindow(){
  window.print();
}
function closeWindow() {
  window.close();
}
function createLink(url,text,func){
  var temp = document.createElement('a');
  temp.setAttribute('href', url);
  temp.appendChild(document.createTextNode(text));
  temp.onclick = func;
  return temp;
}

Step 2: Use clever variable and function names

This is basic good coding practice, although you see it done badly a lot. Once again, quick fixes and looming deadlines are to blame. In essence it means that you use variable and function names that tell the maintainer immediately what this chunk of data is. You can use underscores or camelCase to concatenate different words - personally I prefer camelCase, as that is consistent with the methods JavaScript provides you with (eg. getElementsByTagName()). It might even be a good idea to use generic names for variables that are just computed inside a function or loop and don’t need maintaining like the ‘temp’ variable inside the createLink() function in the earlier example.
Take a leaf out of the book for good CSS design - make sure to keep your function and variable names generic and describe a task rather than a visual result. A createFatRedBoxForLeftNavigation() might become a createTopBarForSectionNavigation() in another code iteration but doesn’t have to if you had called it createSecondaryMenu() from the start.
It is also a very good to stick to English variable and function names - you never know if you have to share the code world wide or send it to another country for maintenance.

Step 3: Comment your code

Commenting can save a lot of time and grief. However, you can also overdo it. In tutorials and books you’ll find code that has a comment on each line explaining what is going on. This is because of the intended audience, and makes a lot of sense inside a tutorial but is rather superfluous in live code. Comments are needed when:

There is a section of code that needs maintenance, eg. ‘Change ID names here’ There is a section that might become outdated as it fixes a problem for user agents that are hip right now There is a reason why you programmed something in one way while there might be better ones and you want to explain that The code section is dependent on another script or gets parameters whose origin may not be obvious at first.

Step 4: Keep your scripts self-contained

This step ties in with unobtrusive JavaScript, so let’s not dwell on it. In essence it means that a maintainer could add your script to any page and don’t risk overwriting other code by doing so. You can keep scripts self-contained by namespacing them or wrapping them in an object via the object literal. You ensure you don’t hijack variables by keeping them in scope of your functions via the var keyword and you don’t hijack events by using addEvent() or its derivates.

Step 5: Keep maintained variables separate and test dependencies

This step is simple: Keep variables that need to be maintained at the beginning of the function and pre-set them with dummy values if necessary. That way the maintainer always knows where to change settings and doesn’t have to scan through the whole script and you won’t run into ‘not defined’ errors.


function toolLinks(){
  var tools, closeWinItem, closeWinLink, printWinItem, printWinLink;

  // link labels, please edit
  var printLinkLabel = ‘print’;
   var closeLinkLabel = ‘close’;#

   tools = document.createElement(’ul’);
   closeWinItem = document.createElement(’li’);
   closeWinLink = createLink(’#', closeLinkLabel, closeWindow);
   closeWinItem.appendChild(closeWinLink);
   tools.appendChild(closeWinItem);
   printWinItem = document.createElement(’li’);
   printWinLink = createLink(’#', printLinkLabel, printWindow);
   printWinItem.appendChild(printWinLink);
   tools.appendChild(printWinItem);
   document.body.appendChild(tools);
}

Testing for dependencies is a trait of Unobtrusive JavaScript - you test for the existence of HTML elements before you access them via DOM methods. Taking this idea further, make sure you test if there are any dependencies in your scripts and alert the maintainer if there is a problem. This is a big issue with a lot of JavaScript libraries. Scripts that rely on the Yahoo! User Interface library will throw an error when it is not available, this could be prevented by testing for it and showing an alert instead. Jquery is even worse as it seems to suppress any errors, which makes debugging a gamble.

Step 6: Separate and communicate the visuals

When it comes to Unobtrusive JavaScript there is no way around applying and removing CSS class names dynamically to and from elements. There is hardly any situation where you need to access the style collection of an object directly, lest you want to make it harder for the maintainer. Exceptions are drag and drop interfaces, but even then all you change via JavaScript is the x and y coordinates of the element. The rest of the look and feel should stay where it was meant to be: in the CSS file. This ensures that CSS designers don’t mess around with your code and you don’t need to know all the ins and outs of CSS bugs in browsers - and there are a lot more than we’d like there to be.

The most basic way to communicate the names of these classes is keeping them in variables and commenting them at the beginning of your script:


demo = {
  // CSS classes
  hideClass : 'hide', // hide elements
  currentClass : 'current', // current navigation element
  hoverClass : 'over', // hover state
  [... rest of the code ...]
}

If you want to go even further in your separation then you could create an own include file called for example cssClassNames.js and use a JSON notation in this one.


css={
  'hide' : 'hide', // hide elements
  'current' : 'current', // current navigation element
  'hover' : 'over', // hover state [... and so on for a lot of them...]
}

In your script you can reach the different class names with css.hide or css.current respectively. You could even use more natural labels like ‘hide elements’ and reach them via css ‘hide elements’, which’ll make it easier for the maintainer but harder for you as a coder.
One really easy trick is a class name to communicate with the CSS designer that you apply to the body of the document. This will allow the CSS designer to distinguish between styles that are applied to the non-JavaScript version and to the scripting enhanced version respectively.


  if(!document.getElementById || !document.createElement){return;}
  cssjs('add',document.body,'jsenabled');

CSS:


/* No JavaScript */
#nav li{
  [...settings...]
}
/* JavaScript */
body.jsenabled #nav li{
  [...settings...]
}

This is also very handy to hide a lot of elements via CSS instead of looping through all of them. In extreme cases, where you have a lot of styles and totally different settings for the scripting enabled version, you could even apply a totally different style sheet via JavaScript (either use document.write() or create a new LINK element).

Step 7: Separate textual content and code

The same tricks apply to textual content, you can either separate labels out as variables or - even better - into an own document called textContent.js in JSON format. An example that worked exceptionally well is this one:


var locales = {
  'en': {
    'homePageAnswerLink':'Answer a question now',
    'homePageQuestionLink':'Ask a question now',
    'contactHoverMessage':'Click to send this info as a message',
    'loadingMessage' : 'Loading your data...',
    'noQAmessage' : 'You have no Questions or Answers yet',
    'questionsDefault': 'You have not asked any questions yet',
    'answersDefault': 'You have not answered any questions yet.',
    'questionHeading' : 'My Questions',
    'answersHeading' : 'My Answers',
    'seeAllAnswers' : 'See all your Answers',
    'seeAllQuestions' : 'See all your Questions',
    'refresh': 'refresh'
  },
  'fr': {
  },
  'de': {
  }
};

It allowed the editorial staff to translate and maintain the labels in all the different languages without having to touch the code. I even managed to separate the IDs out for them to sort out with the HTML developers. All the JavaScript had to do was to read out the application’s locale setting and loop through the elements available:


  function doI18N(){
   var lang = yhost.PluginLocale;
   for(i in locales[lang]){
     if(document.getElementById(i)){
       document.getElementById(i).innerHTML = locales[lang][i];
     }
   }
  }

Step 8: Document your code

Last but oh so not at all least: write documentation about your script / library / effect. Good documentation takes the audience into consideration, which means that for some libraries it is good to keep it a classic API documentation with all possible properties and parameters of methods explained in ‘techspeak’, but in general I have had much more success with ‘Explain by example, then list all possibilities’ documentation. Good documentation saves the most time and money, actually a shame we hardly get the time to create it. Other programming languages tend to automatically generate documentation from code comments (PHP for example), however that does not necessarily make for better docs, just less work.

What about high traffic sites?

If you are working in a high traffic environment, or one that only allows for small code packets (mobile market) then you might frown upon the ideas explained here as they can bloat the code. The way around that problem is to maintain a code base and a live code repository, which is generated from the original code after stripping out the comments, replacing long variable names with shorter ones and performing other packing and minifying tasks. Tools to do that for you are Douglas Crockford’s jsmin and Dean Edward’s packer.

Summary

I hope that the above examples have given you an idea how to make your code more maintainable or reminded you of some ideas that lay dormant in the back of your head. If you have other ideas, or you strongly disagree with some of the practices (and you have good reason to), please drop a comment here, as with everything that is ‘best practice’, it is a work in progress and collaboration can only make it better.

You can find out more about this subject, plus get a podcast from a recent talk Christian gave on the subject at MuffinResearch

digg.com logo Like this article? Digg it!

The Future of Web Design is back in New York, 3-4 Nov, bringing you our fresh blend of amazing speakers, great advice and tons of networking potential. Use our special code FOWD/Vitamin to get a 15% discount!

88 Responses to “The Importance of Maintainable JavaScript”

Dustin Diaz says

Wonderful. A lot of good practices listed here. On the matter of style it’s good (like you mentioned) not to get into the antics of tabs vs spaces, semi-colon insertion, always having curly braces etc… but that the most important factor is consistency. Although a general base of style is good to follow and can most definitely help within a larger environment of coders, it still needs to be consistent in the end.

Furthering the subject of structure and logic, I was wondering what some folks might think on declaring variables, if it would be a silly practice to always declare them at the beginning of a function, rather than throughout the function.
Eg:
function foo() {
var a, b;
// do stuff here
var c, d
// more stuff
}

Would it be better to put ‘a, b, c, d’ all up at the front? Or is that getting a bit to whiny over style. Would that be considered “consistently inconsistent?”

picture of Christian HeilmannChris Heilmann says

Ola Dustin, that is actually in point 5

“This step is simple: Keep variables that need to be maintained at the beginning of the function and pre-set them with dummy values if necessary.”

However, with non-maintained variables, as in just iterators and temporarily necessary ones I don’t see much danger in scattering them around the document, as long as the ones that need changing remain in one spot. I remember some older GWBasic or other horrid language examples that started with a truckload of DIM lines before you reached the code :-)

IONCANNON » Good article on keeping javascript maintainable says

[…] Vitamin has a good article today on the importance of maintainable javascript. 95% of what the article covers is applicable to any code. The important parts of the article cover javascript specific things like: object literals, namespaces and where to go when you want to compress your javascript to save bandwidth. They recommend packer and JSMIN as two javascript compressors but I think JSMIN is probably a better bet mainly because you can run it from the command line and make it part of a build script.          […]

Dustin Diaz says

Chris,
And to think I thought I read every line of the article. I most definitely missed that part. That makes complete sense.

enej says

What do you guys think about the idea of including a stylesheet when no js is enables using the html tags? I know you would have to maintain 2 stylesheets but it might be a way to control the page layout if javascipt is enabled or disabled?

enej says

the noscript HTML tags

picture of Christian HeilmannChris Heilmann says

@enej: I am strongly opposed to using the NOSCRIPT tag, as it does mean you mix structure and behaviour.

NOSCRIPT is greaceful degredation whereas we should think in terms of progressive enhancement - building for the future rather than for the past.

So instead of using NOSCRIPT it makes a lot more sense to create a new LINK element with the JS pulling in a CSS. I really and honestly don’t see ANY point in NOSCRIPT - if you just think about it the other way around.

Check the example I did for avoiding NOSCRIPT way back… Look at the source and test it with JavaScript on and off to see the difference.

picture of Christian HeilmannChris Heilmann says

To those “discussing” this article on digg.com: Please take the following part of the article fully into consideration:

Yes, some of the steps may be very obvious to the jet-set, well travelled and seasoned JavaScript developer, but it can’t hurt to remind ourselves of their virtues.
Furthermore, I dare any one of you to look at some older code and test it against them […] Scope and feature changes together with looming deadlines and budget cuts breed bad code; it is a fact of software development.

You are right that there is not much new here and that these principles can be applied to any programming language. The difference with JavaScript is that for almost a decade not many people took JS serious enough to apply them, and now we have to wade through lines and lines of unreadable code. The other aspect is that JavaScript is a language that attracts a lot of developers that don’t have a programming background, as it allows you to create visual effects and ties in very closely with CSS and HTML. Never assume that everybody knows what you know and things are as obvious.

Nick says

Good read.

P.S. The link to jsmin is broken.

Javascript-Channel.com » The importance of maintainable JavaScript code. says

[…] Christian Heilmann has written an article on the importance of writing maintanable JavaScript.  Advice ranges from simple ideas such as adding comments to your code and having functions do just one thing to some more grandiose concepts such as textual content from code.  His core theme is about writing code that is maintainable and also as reusable as possible.  Although this article is aimed directly at the JavaScript crowd, a lot of this advice carries over to any language. […]

Anonymous says

The Importance of of Maintainable Javascript…

So heres an eight step plan to show you what can be done to make your scripts easier for the maintainer. Yes, some of the steps may be very obvious to the jet-set, well travelled and seasoned JavaScript developer, but it cant hurt to remind ourselves o…

Dustin Diaz says

Chris,
don’t ever, ever, EVER take the comments on Digg seriously. They rarely ever know what they’re actually talking about. Let the professionals discuss the good things here and the diggers do their dance over there. :)

EveryDigg » Blog Archive » The Importance of Maintainable JavaScript says

[…] Chris Heilmann has 8 steps for keeping JavaScript cleanread more | digg story […]

Pig Pen - Web Standards Compliant Web Design Blog » Blog Archive » The Importance Of Maintainable JavaScript says

[…] The Importance Of Maintainable JavaScript can’t be under-emphasised. Even many big name JavaScript gurus write obfuscated code but this is software engineering so certain truths apply. […]

Archatas says

I find many suggestions of yours very handy. You are in my del.icio.us list now :)

Programar mal es programar 2 veces » aNieto2K says

[…] Si hicieramos caso a nuestros padres en todos los aspectos de nuestras vidas, sin duda nos sería más facil vivir en este mundo. De pequeño siempre me dijeron que las cosas se tenían que hacer bien, ya que si las hacía mal al final tendría que hacerlas 2 veces. En la programación siempre lo has de hacer 2 o más veces así que asegurate de hacer las cosas bien para que en un futuro te sea más cómodo. […]

All in a days work… » Blog Archive » links for 2006-07-18 says

[…] The Importance of Maintainable JavaScript - really nothing new here Clean and Logical Syntax and Structure, Use clever variable and function names, Comments, Keep scripts self-contained, Keep maintained variables separate and test dependencies, Separate and communicate the visuals, Separate textual content and code… […]

Testing The Web Dot Com » Blog Archive » The Importance of Maintainable JavaScript says

[…] It’s one thing to develop code that runs well and that does the job, but without structure and formating as a practice in your development, things can get pretty scary pretty quick. Even this new article from Vitamin reinforces the fact. […]

Kae Verens says

a method I use for commenting also helps me to create navigable code. I use vim for coding, which allows me to “fold” at the ‘{’ mark, making blocks and functions into hierarchical trees

a useful thing about this, is that you can then place your comment after the ‘{’.

for example, check out http://kfm.verens.com/sandbox/editor/plugins/kfm/kfm.js

scattered throughout the code, you can find blocks starting with “{ //”.

A handy thing about the {..} syntax, is that it doesn’t actually need to follow an if/function()/for() qualifier! This means that you can logically separate your code into blocks of contextually similar code.

Handily, kdevelop and other IDEs also allow you to fold at the’{’ mark.

Another useful thing, is that this trick also works in PHP.

self-promotion: check out http://kfm.verens.com/

» commented blocks of code » klog says

[…] I was reading an article about maintainable JavaScript, and thought I’d comment on it about a method I use to keep my own JavaScript clean. […]

The Inside Of My Head » links for 2006-07-17 says

[…] The Importance of Maintainable JavaScript JavaScript is hip again; there’s no doubt about it. But if you’re starting to get down and dirty with it, there’s no excuse not to keep it clean. (tags: webdev javascript) […]

Maintainable JavaScript - The Web Standards Project says

[…] In my opinion, this kind of straightforward, practical advice can’t be repeated often enough. That’s why I recommend you read Christian’s article in Think Vitamin. It’s packed full of good advice. […]

Laurent says

Does the memory leak in the code examples not bothering anyone here?

picture of Christian HeilmannChris Heilmann says

@Laurent: No, as they are code examples in this case. Without seeing the rest of the application there is just no knowing if they leak or not - maybe there is a cleanup routine?

You are welcome to fix possible issues and post them here though.

Frank Stepanski says

Chris,

Great article and great website you have, You have taught me a lot about JavaScript and how to use it effectively. I am waiting for your book to get delivered…Hopfully this week!!! yay!

Thanks.

Lori says

http://www.helpsophie.com

Laurent says

Hi Chris,

Found below the updated code I have not re-write anything in your code simply re-order it.

The cleanup routine is really simple soon as you create an element append it to the DOM and keep doing what you want with the reference of that element.

There is a pretty interresting article from microsoft explaining this in details let me know if you want the link.

function toolLinks(){
var tools = document.createElement(’ul’);
document.body.appendChild(tools);
var item = document.createElement(’li’);
tools.appendChild(item);
var itemlink = document.createElement(’a');
item.appendChild(itemlink);
itemlink.setAttribute(’href’, ‘#’);
itemlink.appendChild(document.createTextNode(’close’));
itemlink.onclick = function(){window.close();}
var item2 = document.createElement(’li’);
tools.appendChild(item2);
var itemlink2 = document.createElement(’a');
item2.appendChild(itemlink2);
itemlink2.setAttribute(’href’, ‘#’);
itemlink2.appendChild(document.createTextNode(’print’));
itemlink2.onclick = function(){window.print();}
}

You can make this a lot more readable by indenting and separating each task out into own functions:

function toolLinks(){
var tools = document.createElement(’ul’);
document.body.appendChild(tools);
var item = document.createElement(’li’);
tools.appendChild(item);
var itemlink = createLink(’#', ‘close’, closeWindow);
item.appendChild(itemlink);
var item2 = document.createElement(’li’);
tools.appendChild(item2);
var itemlink2 = createLink(’#', ‘print’, printWindow);
item2.appendChild(itemlink2);
}
function printWindow(){
window.print();
}
function closeWindow() {
window.close();
}
function createLink(url,text,func){
var temp = document.createElement(’a');
temp.setAttribute(’href’, url);
temp.appendChild(document.createTextNode(text));
temp.onclick = func;
return temp;
}

Dustin Tinney says

It’s sad that never once did unit testing your JavaScript get mentioned. I think unit testing is a key feature left out of web development and I’m said that some of the top writers on the subjects aren’t pushing for it.

picture of Christian HeilmannChris Heilmann says

Unit testing is the 600 pound Gorilla though and applies to massive JavaScript apps to really be worth while. But you are right that there should be a mention of it. So yes, JSUNIT is a great tool for large scale JS development.

GRoper says

Chris Hellman states:
“NOSCRIPT is greaceful(sic) degredation(sic) whereas we should think in terms of progressive enhancement - building for the future rather than for the past.”

But your example does not work at all if javascript is disabled. That is not graceful degradation, that is failure!

When developers modify the basic WWW GUI, the result is chaos: every site is different and each has different navigation rules and interactions. Users must be trained for each site.

Best is to not use javascript and fall back to the default WWW browser behaviors.

In the long run that is also most efficient, since once latency decreases sufficiently, it does not matter whether processing is done on the client or the server (IIRC the Devil Himself, Bill Gates, said the same years ago).

Justin Palmer says

Great article. I am in the process of writing a similar article, but it’s main focus is on good variable naming. I think we’re the only genre of developers who are willing to sacrifice readability for file size. In return you get a script thats hard to maintain by anyone.

picture of Christian HeilmannChris Heilmann says

@Groper: First of all, that is demo code to show syntax ideas, not a “code example”. Secondly have you taken a closer look at the example?

It creates two links that each call a window method to print or close the window - both of which are only working links when JavaScript is enabled.

The example generates the links when and if JavaScript is available. So could you please explain me how that is a failure?

Both functionalites are repeating what the browser GUI offers you via menus and keyboard shortcuts and in older JavaScript applications developers used javascript:window.close() links for that. These _are_ a failure, as they _promise_ functionality that doesn’t work. This demo code does not promise anything but only offers the functionaliity after testing that it is possible.

There is no non-javaScript way to print or close a browser window programatically, so there is nothing you could offer in a NOSCRIPT tag, except for “print and close this window” which is pretty redundant.

I agree with you that both links are redundant to people who know their browsers, but they can be helpful for beginners. I dare you to take part in some user testing from time to time before talking about ”

And my name is Heilmann (SIC)

picture of Christian HeilmannChris Heilmann says

Sorry, submitted too early. What I wanted to add was that there is no “default browser behaviour” as such, as every user fulfils tasks differently (for example I use ctrl+r to reload a page instead of pressing F5).

Generalisation or projection of what YOU think is right and good and “common knowledge” is hardly ever a clever move (that is a generalisation, but what the heck).

Val says

@laurent,
Interesting technique to append a new node immediately after you create it, rather than build it up separately and append at the end. Please post the link to the MS article — I’m interested in specifically why this avoids memory leaks. I think I see the difference, but I’d rather not guess.

Thanks!

CSS Greut » Maintainable JavaScript says

[…] Chris Heilmann doet een goede voorzet om met The Importance of Maintainable JavaScript licht in de duisternis te werpen: So here’s an eight step plan to show you what can be done to make your scripts easier for the maintainer. […]

A importância de JavaScript reutilisável | Batutinhas Nerd Blog says

[…] Pois bem, nos últimos 3 meses tenho trabalhado bastante com JS (String JS = “JavaScript”) e estou quase conseguindo não ter pesadelos com ela durante a noite. (embora eu ainda prefira JSON à AJAX, mas isso é assunto para outro post). Na minha “hora do intervalo” diária, estou lendo (como sempre, estou postando sem terminar de ler hahaha) um artigo FODIVELMENTE ENGRAçADO se não fosse trágico que trata justamente da reusabilidade, manutenibilidade de legibilidade de códigos javascript… Eu tive de interromper a leitura do artigo para analizar o código que eu estava gerando e quase morri de vergonha. Tenho TRIPAS de JS com 90% das coisas que eles não-recomendam ali hahahaha […]

Vinny Carpenter’s blog · Daily del.icio.us for Jul 18, 2006 says

[…] Vitamin Features » The Importance of Maintainable JavaScript JavaScript is hip again; there’s no doubt about it. But if you’re starting to get down and dirty with it, there’s no excuse not to keep it clean. (tags: javascript programming tips ajax development standards best-practices code) Tags:Bookmark this page at:These icons link to social bookmarking sites where readers can share and discover new web pages. […]

Vinny Carpenter’s Link blog » Blog Archive » links for 2006-07-18 says

[…] Vitamin Features » The Importance of Maintainable JavaScript JavaScript is hip again; there’s no doubt about it. But if you’re starting to get down and dirty with it, there’s no excuse not to keep it clean. (tags: javascript programming tips ajax development standards best-practices code) Explore posts in the same categories: Daily Links […]

links for 2006-07-19 | Musings by Steve Miller says

[…] Vitamin - The Importance of Maintainable JavaScript (tags: javascript programming tips ajax development webdev webdesign) […]

Script Artists » Archiv » Maintainable JavaScript says

[…] The Importance of Maintainable JavaScript […]

Silhouette.wordpress.com » The Importance of Maintainable JavaScript says

[…] read more | digg story […]

Laurent says

@Val,

Found below the link to the microsoft article
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/IETechCol/dnwebgen/ie_leak_patterns.asp

I got a few more really interresting link on here if you need.
http://del.icio.us/laurent.muchacho/memoryLeak

Laurent

The Importance of Maintainable JavaScript > Archives > Web 2.0 Stores says

[…] writing maintainable Javascript That last one throw you for a loop a bit? Well, read on… It’s one thing to develop code that runs well and that does the job, but without structure and formating as a practice in your development, things can get pretty scary pretty quick. Even this new article from Vitamin reinforces the fact. Forums and mailing lists are full of requests about Ajax, DOM Scripting and how to use this or that library or effect. There is also an extraordinary amount of scripts, libraries and effects being developed and showcased, and the blogs and news sites specialising in scripting hardly have time to look at the demos properly before they are on Digg.com or del.icio.us and making the rounds from these sites. Times to celebrate for those who have hung on to their skills when the DHTML craze subsided in 2001 and JavaScript became persona non grata on your CV as a main skill. They talk about not only some of the benefits of having well-maintained scripts (making the user’s life easier), but some techniques to help you keep things neat in your own work. They make suggestions like “Keep your syntax and structure clean and logical”, “Seperate textual content and code” and “Comment your code” (funny how that last one pops up so often, eh?) All in all, they give you eight different tips on how to “keep it clean” when it comes to creating code, all with descriptions/explainations and code examples where appropriate. July 17th, 2006 […]

Lynred says

Hi Chris,

Maybe a slightly off topic here but what if I need to exclude 5 external scripts to load in IE 5 MAC, good CSS but advanced DOM: a no go there.

Any try and catch tips

Willspace » Career changing books says

[…] Vitamin recently posted an article about the importance of developing maintainable JavaScript. This is a useful and well written article although it doesnt offer anything revolutionary. I would say pretty much all the points are applicable to almost any type of development, and for JavaScript developers (or indeed any developers) to whom these concepts are new, I would recommend they grab a copy of Code Complete by Steve McConnell. This got me thinking about all the books / blogs that have really changed my perspective around software engineering and why, so, in no particular order… […]

Digi says

Combining scripts which have inconsistent coding styles is not fun at all. Can someone recommend code beautifier (or editor that includes one) for JavaScript which has adjustable formatting options?

Project Syndicate » Blog Archive » England 2006 says

[…] His whole presentation sort of whizzed by, and he kept everyone laughing most of the time. I could go more in-depth, but the crux of what he said is also contained in his recent article on Vitamin, entitled The Importance of Maintainable JavaScript. Sprinkle in a few references to drinking and imagine him poking fun at Andy for being a certified diving instructor, and you’ve got the essence. Also, get his book JavaScript with DOM Scripting and Ajax… […]

Dan Acuff says

Digi

Do you mean something like Notepad++ ??

Link: http://notepad-plus.sourceforge.net/uk/site.htm

Programming » The Importance of Maintainable JavaScript says

[…] Chris Heilmann has 8 steps for keeping JavaScript cleanread more | digg story […]

Javascript Blog » Blog Archive » Keeping Javascript clean says

[…] Think Vitamin has an article up about keeping your Javascript clean and maintainable. The value of following these 8 steps is invaluable in creating code that is easy to read and logical for whoever has to read it. Sure, some of the tips here are fairly obvious to the hardcore JS coder, but it is good to review. Read through the article and test it against your current practices. Explore posts in the same categories: Javascript […]

Ken Dryden says

What Is Good JavaScript?

Keeping code maintainable

separation of maintained variables and functional code –

variables first, then code.

clear communication of generated CSS class names – if

necessary as an own JSON object

separation of labels and other text content of generated code
—————-
Ken,
http://pointniche.org

torrie wilson in a thong says

torrie wilson in a thong

http://myblog.es/torrie-wilson

trish stratus porn says

trish stratus porn

http://myblog.es/trish-stratus

özel siteler says

Can I use Javascript code in php echo tag?How can I use it? thanks.

selcuk says

ooo its good. javascript is basic and wonderfull.

msn ifadeleri says

javascript is basic but,I dont understand..How I learn it? ..thanks for article.

Video indir says

Site Ekle

e-kart,resim,ÅŸiir says

ı cannot use javascript but ı know ıt has big importance on sites..
thanks..

msn adresleri says

does the memory leak in the code examples not bothering anyone here?

güzel kızlar says

Can I use Javascript code in php echo tag!!??

oyunlar says

good java script.

komik videolar says

video script

burçlar says

Thank you

Venus says

Thanks for this.

lazer epilasyon says

thanks

kız oyunları says

thank you very much…

kraloyun says

very nice

resimler says

thanx. very nicee..

Msn Ifadeleri says

Why we have to write # after var closeLinkLabel = ‘close’; ?

video izle says

javascript is basic and wonderfull.

sohbet says

Think Vitamin has an article up about keeping your Javascript clean and maintainable. The value of following these 8 steps is invaluable in creating code that is easy to read and logical for whoever has to read it. Sure, some of the tips here are fairly obvious to the hardcore JS coder, but it is good to review. Read through the article and test it against your current practices. Explore posts in the same categories: Javascript

ikinci el eÅŸya says

I didn’t like the fixes as they didn’t have the grey boxes on either side for the single and page templates, so didn’t suit my purposes, as I wanted those to stay.

I have the site working now, mainly by having taken out the comments option, it seems that was what was throwing things out in IE. I couldn’t work out how to change it. If you ever sort this glitch properly please let me know!

video says

thank lan :D

youtub says

saÄŸol be :)

gazete says

thanks

Estetik says

thank you

kraloyun says

very nice comments

sohbet says

very nice comments

Emre says

Explain by example, then list all possibilities’ documentation

mirc says

i think google doesnt like .js webpages

ilan says

Can I use Javascript code in php echo tag?

mirc says

very nice comments

evden eve nakliyat says

Kae waren say my answer: {..} syntax, is that it doesn’t actually need to follow an if/function()/for() qualifier! This means that you can logically separate your code into blocks of contextually similar code.

site ekle says

{..} syntax, is that it doesn’t actually need to follow an if/function()/for() qualifier! This means that you can logically separate your code into blocks of contextually similar code.

Javascript News » Blog Archive » Keeping Javascript clean says

[…] Think Vitamin has an article up about keeping your Javascript clean and maintainable. The value of following these 8 steps is invaluable in creating code that is easy to read and logical for whoever has to read it. Sure, some of the tips here are fairly obvious to the hardcore JS coder, but it is good to review. Read through the article and test it against your current practices. […]

The Importance of Maintainable JavaScript « See the Post says

[…] read more | digg story Posted by seethepost Filed in news […]

Olkenava » Blog Archive » The Importance of Maintainable JavaScript says

[…] read more | digg story […]

mp3 buy online » Blog Archive » The Importance of Maintainable JavaScript says

[…] Chris Heilmann has 8 steps for keeping JavaScript cleanread more | digg story […]

Comments RSS


You are viewing a mobilized version of this site...
View original page here

Mobilized by Mowser Mowser