Tuesday, October 11, 2011

How to write a good Javascript widget

Writing a Javascript widget is almost easy but I learnt at my expense that it may be tricky. So I wrote some simple rule that help to do the job well.

1 - keep in mind: progressive ehnancement
I already wrote about it, just a recap: write html semantically correct (your mark up MUST have sense even WITHOUT Javascript)
2 - do not use inline styling (use CSS)
When your script are about to create your widget, find the outermost element and give to it a specifical class. Then do not attach style directly to the DOM elements, instead use CSS.
In this way you can customize the style of your widget without touching a single line of Javascript.
3 - avoid FOUC
Usually you modify the DOM after it is loaded. That way you may see the page while change. This is called FOUC (flash of unstyled content). You can avoid this hiding the DOM nodes you are about to change (using CSS) and show after (using Javascript).
Just a suggestion: you can use a noscript tag to show what you have hidden before in case Javascript is not enabled.
4 - use a library
A library like jQuery helps a lot with the DOM manipulation, It helps to forget the differences between the browsers. You can find a thorough guide to make a plugin here.
5 - do not calculate size and position during the widget creation
You can't assume what part of your page will be displayed and when. So you can't calculate position and size of elements at creation time. An example: I used this spinner widget on my application (http://btburnett.com/spinner/example/example.html). The widget calculates the input dimension and adds a lot of on-line styling for the little arrows. But in my application display the widget inside an hidden tab and all the size calculation returns wrong results.