JavaScript on Modern Web

JavaScriptly


Archive for August, 2008


JQuery Site Re-redesign

The redesign of JQuery DOT COM site recently gained a huge amount of comments; unfortunately most of them were not positive. Developers who have come along with the library feel unhappy with new slogan “Be a Javascript Rockstar” that, said, makes them look unprofessional.

Response to a post on Ajaxian, shypht commented:

Hate to say it, but image is everything. If I was trying to sell my manager on using jQuery, Prototype, Mootools or Dojo, and sent them to those sites, I think based on look alone jQuery would be at a disadvantage. “Write less, do more” is a great slogan, “Be a Javascript Rockstar”, not so much.

Strikes me as being an amateur, and more focused on flashy effects than functionality. I love jQuery, it’s helped me loads on my most recent project, but that header just makes me cringe a bit on the inside when I see it.

While Glen Lipka described his feeling in more colorful words on his blog post:

Truthfully, I feel alienated by it.  It doesn’t resonate with me.  It makes me feel old and lame.  My hair is not long and flowing. The rockstar isn’t me.  jQuery is me.  It’s different.

Obviously John Resig & team did listen to the community and decided to kill the “JavaScript RockStar” on JQuery site.

Apart from the new glossy UI, the best of JQuey site’s new design is to organize documentation for the library itself separately from hundreds of plugins and extentions. The new search functionality allows user to fine tune query to specific documents or keywords.

Well, however, please keep in mind that nobody want to be a JavaScript rocktar! :)

Share and Enjoy:
  • description
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • Mixx
  • SphereIt
  • TwitThis
  • NewsVine
  • Google
  • Technorati
  • Facebook

YUI 3.0 – Changes From the Root

If you are web developer you may have noticed that the latest version of Yahoo’s User Interface toolset and widgets (for web development), YUI 3.0, is now available as a preview release. YUI has long been a popular “Ajax” library both because of its liberal BSD license, and because of the number of features it provides.

The big news about YUI the third are that it changes from the root and (unfortunately) is not compatible with YUI 2.x APIs as Eric and Matt stated on developer blog.

YUI 3.0 builds off of the YUI 2.x codeline, but we’ve evolved most of the core APIs in working toward the five key goals described above. As a result, migrating from YUI 2.x to 3.x will require effort at the implementation level.

However, YUI 3.0 will ship with a limited compatibility layer for the current YUI Core that will allow you to run some of your YUI 2.x-based implementations (Yahoo Global Object, Dom Collection, and Event Utility) on top of YUI 3.0.

These radical changes are toward 5 goals:

  • Lighter (less K-weight on the wire and on the page for most uses)
  • faster (fewer http requests, less code to write and compile, more efficient code)
  • more consistent (common naming, event signatures, and widget APIs throughout the library)
  • more powerful (do more with less implementation code)
  • more securable (safer and easier to expose to multiple developers working in the same environment; easier to run under systems like Caja or ADsafe)

So, what’s new in YUI 3.0? Many things, both large and small like:

  1. Intelligent loading. YUI detect which modules it needs to load, and then download them from a server — it will also join the modules’ JavaScript source files together, in order to optimize download time.
  2. Change to a “YUI” namespace instead of “Yahoo” namespace in YUI 2.x branches.
  3. Combine DOM events with custom events, making it possible to work with all events in a unified way.
  4. Borrow “selectors” idea from JQuery to allow finding and working with nodes on an individual and group basis.
  5. Chaining - another JQuery’s idea that makes it possible to write more compressed chaining syntax in implementation code.

Now you can jump into examples to see the lib in action, especially the nice “Portal Drag” example created by Dav Glass which loads only 8 KB JavaScript files (after gzipped) at first.

Hope I’ll have time to create examples to show YUI 3.0 functionality in practice.

Share and Enjoy:
  • description
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • Mixx
  • SphereIt
  • TwitThis
  • NewsVine
  • Google
  • Technorati
  • Facebook

A Better JavaScript Template Engine

Rizqi Ahmad from Germany has introduced a nice solution for client-side template based on JQuery. The Chain.js allows you to use any piece of HTML (or embedded HTML string) as template to display data dynamically.

In introductory post, he went through some common approach like server-side data binding, injecting preformatted HTML (into well-known DOM property innerHTML) and directly manipulating DOM, then explained why Chain.js is better way:

  1. Easy and compact (as it uses JQuery for manipulating DOM)
  2. Preserve event(s) on updates
  3. Allow dynamically add/remove data

To use the engine, you’ll need to download JQuery (better the latest version) and Chain.js then add script tags to load them.

<script src="path/to/jquery.js" language="javascript"> </script>
<script src="path/to/chain.js" language="javascript"> </script>

Practical Example on Chain.js

Now, we’ll create a practical example that allows user select a programming language and display recommended reading books accordantly. This is almost similar to another example I created for PURE library.

First, build a template table to display book list:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<table class="books">
<thead>
		<tr>
			<th>Title</th>
			<th>Publisher</th>
			<th>Price</th>
		</tr>
	</thead>
	<tbody id="book_table_body">
		<tr class="item">
			<td class="title"> </td>
			<td class="publisher"> </td>
			<td class="price"> </td>
		</tr>
	</tbody>
</table>

Second, get data (books) from server based on selected language selected via Ajax using JQuery function $.getJSON().

1
2
3
4
5
$.getJSON('json.php', 'lang=' + $('#langList').val(),
	function(books){
		........
	}
);

We’ll have a list of books in JSON format that looks like:

[{title: "Sams Teach Yourself Java 6 in 21 Days", publisher: "Sams", price: 29.69},
{title: "Java In A Nutshell", publisher: "O'Reilly", price: 29.67},
{title: "Effective Java", publisher: "Sun", price: 28.79}]

Then just tell Chain to parse the books and add them to the table body:

$('#book_table_body').items(books).chain();

All JavaScript codes to get it work are as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
function render(){
	$.getJSON('json.php', 'lang=' + $('#langList').val(), function(books){
		$('#book_table_body')
		.items('destroy') 	/* clear previous items */
		.items(books)		/* parse items */
		.chain();		/* chain them */
	});
}
 
$(document).ready(function(){
	$('#langList').change(render); 	// handle change event of drop-down list
	setTimeout(render, 100); 		// call render function on load
});

See this example online: Example 1. Select each language to see the book list below changed.

Add/Remove & Sort Items

Chain.js supports adding, removing and sorting items with minimal efforts. To visualize the functionality, we’ll create some INPUT fields to add new data to the book table.

1
2
3
4
5
6
<div class="add-data">
	Title: <input id="input_title" type="text" width="10" />
	Publisher: <input id="input_publisher" type="text" width="10" />
	Price: <input id="input_price" type="text" width="10" />
	<input type="button" value="Add" onclick="addData()" />
</div>

Then, define addData() function that responses to “onclick” event of Add botton :

1
2
3
4
5
6
7
function addData(){
	var data = [{title: $('#input_title').val(),
			publisher: $('#input_publisher').val(),
			price: $('#input_price').val()}];
 
	$('#book_table_body').items('add', data);
}

To support removing a row by double clicking on it, we’ll bind the event on chain method:

1
2
3
4
5
6
7
8
$('#book_table_body')
	.items('destroy') 	/* clear previous items */
	.items(books)	/* parse items */
	.chain(function(){ /* bind event */
		this.dblclick(function(){
			$(this).item('remove'); // remove item
		});
	});

The last functionality we wish at the moment is to sort items. First, we have to create some links on table header:

1
2
3
4
5
6
7
8
9
10
<table class="books">
	<thead>
		<tr>
			<th><a href="javascript:void(0)" onclick="sortBy('title')">Title</a></th>
			<th><a href="javascript:void(0)" onclick="sortBy('publisher')">Publisher</a></th>
			<th><a href="javascript:void(0)" onclick="sortBy('price')">Price</a></th>
		</tr>
	</thead></table>

And define sortBy() function to handle sorting items by column, not complicated as you may think:

1
2
3
function sortBy(col){
	$('#book_table_body').items('sort', col, {toggle:true});
}

That’s all. Please see online example: Example 2 and feel free to add items, to remove one by clicking on the row and sort them (ascendant or descendant).

Advanced Custom Data Binding

The last example is to explore a bit advanced functionality which I find very useful in practice: custom data binding. As you can see in the above examples, data binding are made by default: Chain.js matches data field with element class name and render text into it. In practice, it’s very often that we want to format or bind data to sub-elements instead.

For example, now we want to:

  1. Format “Price” to fixed 2 decimal, add a dollar sign before number and make it align at right.
  2. Add another column called “Order” that link to order page (say http://amazon.com/…)

The template table must be modified to add a new column (Order) that contains a link by default:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<table class="books">
	<thead>
		<tr>
			<th>Title</th>
			<th>Publisher</th>
			<th>Price</th>
			<th>Order</th>
		</tr>
	</thead>
	<tbody id="book_table_body">
		<tr class="item">
			<td class="title"></td>
			<td class="publisher"></td>
			<td class="price3"></td>
			<td class="order">
			      <a class="order-link" href="#"></a>
			</td>
		</tr>
	</tbody>
</table>

On chain method, we’ll define a directive to tell Chain how to bind data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$('#book_table_body')
	.items('destroy') 	/* clear previous items */
	.items(books)		/* parse items */
	.chain(
	/* Custom data binding */
		{
			'.price3': {
				style: 'text-align: right',
				content: function(data, el){
					return '$' + data.price.toFixed(2);
				}
			},
			'.order .order-link': {
				style: 'color: red;',
				href: '{orderLink}',
				target: '_blank',
				content: 'Order Now!'
			}
		}
	);

Only problem I found is the custom data binding does not override default one so that I have to rename class of price row to “price3” or Chain won’t parse the directive (but simply use “raw” price number as Example 1). Hope Rizqi Ahmad will fix that in the next version?

Online example is here.

Conclusion

Chain is very nice and comprehensive solution I can find among many others, thanks to compact syntax and simplified DOM manipulate method by JQuery — Just write less and do more with HTML template! Please download all source codes of above examples at the following link.

Update: Revised examples based on Chain.js v0.2 can be found here.

Download source codes

Share and Enjoy:
  • description
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • Mixx
  • SphereIt
  • TwitThis
  • NewsVine
  • Google
  • Technorati
  • Facebook

Turn on JavaScript JIT in Firefox 3.1

Mozilla has just introduced a new JavaScript optimization feature to Firefox 3.1 development code base (Shiretoko) that well enhances JavaScript-based web apps performance by a 2x - 20x fold compared to the Firefox 3.0, according to JavaScript performance tests ran and published by Mozilla’s Brendan Eich.

I’m extremely pleased to announce the launch of TraceMonkey, an evolution of Firefox’s SpiderMonkey JavaScript engine for Firefox 3.1 that uses a new kind of Just-In-Time (JIT) compiler to boost JS performance by an order of magnitude or more.

Here are some of the charts from Brendan’s blog:

assorted-benchmarks

Assorted benchmarks

SunSpider micro-benchmarks

SunSpider micro-benchmarks

However the best way to evaluate it is to see it in action via simple JavaScript image editor that lets you adjust a picture’s contrast and brightness with a couple of sliders created by Mike Schroepfer. By default, TraceMonkey is disabled (as it is still buggy), there is a very noticeable delay while sliding. Turn it on (javascript.options.jit.content = true in about:config) and the thing works like charm, very smoothly.

JavaScript Image Editor

JavaScript Image Editor

Going into significant detail on how all of this came about, Brendan notes some key points:

  • We have, right now, x86, x86-64, and ARM support in TraceMonkey. This means we are ready for mobile and desktop target platforms out of the box.
  • As the performance keeps going up, people will write and transport code that was “too slow” to run in the browser as JS. This means the web can accomodate workloads that right now require a proprietary plugin.
  • As we trace more of the DOM and our other native code, we increase the memory-safe codebase that must be trusted not to have an exploitable bug.
  • Tracing follows only the hot paths, and builds a trace-tree cache. Cold code never gets traced or JITted, avoiding the memory bloat that whole-method JITs incur. Tracing is mobile-friendly.

John Resig says similar opinion in his blog post on the subject:

[This] means that JavaScript is no longer confined by previously-challenging resource of processing power… I fully expect to see more massive projects being written in JavaScript…

The primary thing holding back most extensive Canvas development hasn’t been rendering - but the processor limitations of the language (performing the challenging mathematical operations related to vectors, matrices, or collision detection). I expect this area to absolutely explode after the release of Firefox 3.1 as we start to see this work take hold.

Yes, after the release of Firefox 3.1 we can expect a new wave of web apps and games leveraging JIT JavaScript engine for much better performance without third-party plugins like Flash, Java Applet…

Share and Enjoy:
  • description
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • Mixx
  • SphereIt
  • TwitThis
  • NewsVine
  • Google
  • Technorati
  • Facebook

Is Future of JavaScript in Harmony?


What is Harmony?

What is Harmony?

Many web developers have felt relief to hear that EcmaScript 4 (ES4) standard project fell apart. Through quite a long post “The Only Thing We Have To Fear Is Premature Standardization“, Douglas Crockford told us why EcmaScript standard must be revised to cope up with changes on modern web but ES4 has not been mature enough to be realized.

In deeper details, John Resig explained how current ES4 will not reach a sensible result and why it should be merged with ES 3.1 to create the next specification (code name Harmony).

The ECMAScript 4 specification development was very ad-hoc in nature (primarily tackled by Adobe, Mozilla, Opera, and Google): Implementors agreed upon a set of features that they wished to implement and a specification was molded out of the remaining consensus. Building a specification tailored by implementation is a very pragmatic means of reaching a reasonable result.

However there was a fundamental split related to how much of the specification should be implemented. Enter ECMAScript 3.1. This working group (lead by Microsoft and Yahoo) set out to implement some minor changes and bug fixes to ECMAScript 3 while remaining as a subset of full ECMAScript 4 functionality.

These two groups continued to work side-by-side but a struggle was inevitable. The ECMAScript 3.1 group wanted to add changes to the language that would affect the result of ECMAScript 4. This struggle over the past year finally came to a head this past month at the meeting of TC39 (the committee responsible for both ECMAScript 4 and ECMAScript 3.1). Dubbed “the Oslo meeting” this discussion between the two groups saw an ultimate conclusion: The two efforts had to be merged, otherwise neither one would succeed.

You may be confused with the “name soup” of JavaScript, JavaScript 2, ECMAScript (3, 4 and 3.1), ActionScript, Tamarin etc. Right? Just find clear explanations of such terms from another post by Alex Russell.

So, now (near) future of JavaScript can be seen via the Harmony project with some new features we can certainly expect:

  1. Classes will be a part of the new language but they will be defined as simply being syntactic sugar for a series of plain methods or conventions
  2. New methods like Object.freeze() — which allows you to pass in an object and “freeze” it, preventing it from being modified any further — to create class-like experience.
  3. JavaScript getters and setters (implemented by Mozilla, Apple, and Opera) will be in the specification.

Maybe other topics like “let” or “expression closures” will be considered but as they require new syntax, it’s more likely that they will be in post-Harmony.

One question: Should we still consider Harmony (specs) as JavaScript 2 or we’ll wait for something better?

Share and Enjoy:
  • description
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • Mixx
  • SphereIt
  • TwitThis
  • NewsVine
  • Google
  • Technorati
  • Facebook