Grafico Charts
Grafico is a charting library that provides line, area, stacked and bar graphs, as well as various types of sparklines.
Grafico also includes features like pop-up hovers. All of the features are covered in the documentation.
The API looks like this:
var graph = new Grafico.GraphType($(element), data, options);
So drawing a line graph is easy:

var linegraph = new Grafico.LineGraph($('linegraph'), { workload: [8, 10, 6, 12, 7, 6, 9] });
Grafico is actually based on a library called Ico that I made. Ico has some history behind it: I attempted to replicate the advice in Stephen Few’s books to create a library that intuitively produces usable and clean graphs. I’m still working on Ico — I’ve been benchmarking it to improve speed and remove the Prototype dependency.
Hot Code Loading in Node.js
In Hot Code Loading in Node.js Blaine Cook describes how to dynamically reload code in node.js projects. He’s created a branch of node.js called hotload that provides the feature.
Hot code loading uses sandboxes and caching to reload code when it changes. If you had a web app and updated some files, it would automatically reload the code for new requests.
His example looks like this:
var requestHandler = require('./myRequestHandler');
process.watchFile('./myRequestHandler', function () {
module.unCacheModule('./myRequestHandler');
requestHandler = require('./myRequestHandler');
}
var reqHandlerClosure = function (req, res) {
requestHandler.handle(req, res);
}
http.createServer(reqHandlerClosure).listen(8000);
Strictly speaking it’s not as advanced as the way Erlang behaves, but it could ease deployment and avoid abrupt process reloading.
JSConf.US
It looks like we’re slow to report on JSConf.US but there are still tickets left according to the registration form. Early bird tickets are $500, and the conference is on April 17th and 18th in Arlington, VA.
Speakers haven’t been announced yet, but they have videos up from other conferences. There are also positive comments from CommonJS’s Kevin Dangoor in CommonJS: the First Year.
If you’re running a JavaScript-related conference let us know and we’ll feature it.
The Four Cs of JavaScript
This article is a short trip around some of JavaScript’s more useful features and patterns. Or just my favourite ones that begin with C.
Closure
Closures are your primary tool for controlling, abusing and exploiting scope in JavaScript. In JavaScript, inner functions get access to variables in the functions that contain them.
function say_hello() {
var name = 'Alex';
function say_hello() {
return 'Hello ' + name;
}
return say_hello();
}
In the previous example, name is visible in the function say_hello.
You can use closures to hide variables as well:
person = function() {
var name = 'Alex';
return { say_hello: function() { return 'Hello ' + name; } };
}();
person.say_hello(); # "Hello Alex"
person.name; # undefined
Because closures allow you to capture context, they can provide clever ways of delaying execution whilst retaining the context in which they were defined — callbacks are a common example.
Callbacks
JavaScript’s functions are objects. You can safely pass them around in variables. Libraries like jQuery and Prototype rely on this for event handling and Ajax requests. You can’t make a network request and block until it has completed because this will lock up the UI, so instead you set up an Ajax request with a list of callback functions to be executed later.
The way callbacks and closures work in JavaScript is so simple a lot of developers use them all the time without even realising.
Cascade
Cascading method calls look like this:
new Turtle('Player 1').
move(x, y).
stroke('#ff0000').
fill('#0000ff').
draw();
This is possible because each function returns this, allowing several operations to be performed on the fictional Turtle.
Many libraries use this approach to make manipulating objects more succinct.
Curry
Curry is what I should be eating instead of writing this article. It’s also a slightly trickier devil than the other Cs, but it’s interesting and builds on them.
Currying means changing a function that takes multiple arguments so it can be called as a chain of functions with single arguments. This can be achieved in JavaScript by using a closure.
The Prototype framework has curry and it looks like this:
String.prototype.splitOnSpaces = String.prototype.split.curry(" ");
"foo bar baz thud".splitOnSpaces(); // ["foo", "bar", "baz", "thud"]
Don’t worry if currying seems slightly abstract — come back to the previous example the next time you think you might be able to use it.
HTML5 Video

You’ve probably seen a lot of hype around HTML5 video recently. I’ve been researching open source libraries to see what’s currently available. However, today I found SublimeVideo which is a player that supports seeking, full-window view, draggable controls and keyboard shortcuts.
This really works best in WebKit nightlies. The main reason for this is the fullscreen support and the speed of the effects.
The associated JavaScript is currently copyrighted with a disclaimer that says it can’t be used beyond the demo. The demo is worth checking out though, if only as an example of a strong lightweight JavaScript and HTML-based video player.
qmock
qmock is an expect-run-verify JavaScript mocking library. You can use it to mock objects alongside another testing library.
People generally mock IO-bound services, like network or disk access. The authors suggest that you could use qmock to mock Ajax calls. There’s a note about this in the API documentation:
mock$ = new Mock();
mock$
.expects(1)
.method('get')
.withArguments('some/url', Function)
.callFunctionWith('data response');
// Exercise
var called = false;
mock$.get('some/url', function (data) { called = true });
As this example illustrates, qmock has an API that relies on cascading invocations. This helps the API appear expressive.
There’s some interesting history behind qmock:
qMock was written during our (Mark Meyer // Andy Beeching) tenure at Channel 4 Television, in response for the project requirement of automated testing of all JavaScript code on the site (using QUnit as our test harness). We are grateful to them for allowing us to open-source the project.
JSNES and Emulation

If you haven’t seen JSNES or JSSpeccy they’re worth trying out, if only as a way of proving what JavaScript and canvas can do. The most interesting thing about these emulators, though is the source. JSNES is on GitHub so you can casually browse files like cpu.js to see how the emulator works.
In fact, if you’ve never written an emulator but wondered how they work, JSNES is worth checking out. Emulators aren’t really as scary as they sound: they’re essentially decoders that can understand code for particular hardware and run it in a different environment. They’re giant case statements and simple algorithms.
In JSNES, you can see how the CPU registers and interrupts are handled. Since the original hardware has been reverse engineered there’s nothing fundamentally complicated or difficult to understand, there’s just a sizable amount of code.
Now all we need to do is find the source for an x86 emulator to create a JavaScript PC emulator. Browser VMware could be the most computationally extravagant use of JavaScript yet.
XUI
I was recently reviewing mobile web JavaScript frameworks when I came across XUI, by Brian LeRoux and the other PhoneGap authors. XUI is a micro-framework — it’s designed to be small, portable and concise.
XUI provides the following features:
- Element lookup through selectors
- Events, with support for touch screens
- DOM manipulation
- Animation through tweening
- XmlHttpRequest
The API is available through the global x$. Usage looks like this:
x$('li','.selected', '#some_id'); // Returns elements for a selector or list, similar to $ in jQuery and $$ in Prototype
x$('#video').html('inner', '<strong>Rick Roll</strong>'); // Modifies the HTML of an element
x$('a.save').on('click', function(e) { alert('Saving...') }); // Events
x$('#box').tween([{ left:100px, backgroundColor:'green', duration:.2 }, { right:100px }]); // Tweening
You might be wondering why XUI is smaller and faster than frameworks like jQuery. Ultimately it’s because they’ve cut the cross-browser chaff that we need for cross-browser development. They’ve also tightly focused on mobile web development.
It’s smart of the PhoneGap developers to extract this framework, much like Sizzle was a good idea. In fact, there are enough useful features in it to do a lot without even using the rest of PhoneGap!
Park your Horse, Code Cowboy: Professional JavaScript Workflows, Part 1
When it comes to professional practices, is your JavaScript always stuck with the short end of the stick?
Take this simple quiz to find out. Do you…
- Break up and organize your code into small, easily digestible files?
- Keep only one canonical copy of third-party libraries?
- Use a deployment workflow, to concatenate and minify automatically?
- Automatically generate documentation?
- Unit test your business logic?
Lemme guess—sometimes, no, not really, no, and only when something breaks.
Even the most nitpicky developers tend to treat JavaScript like a red-headed step language. JavaScript is indeed a language that rose from the ashes of heinous hackery. But this is 2010; JavaScript is all grown up now.
There’s never been a better time to learn to treat it that way.
Welcome to the Pro Workflows Series, part 1
In this series, we’ll talk about tools & techniques you can use to cover those No’s, and cut a lot of strife & embarrassment from your JavaScript experience.
Part 1: Break up & organize your code
Spaghetti, with meatballs: Great on your plate, not in your code. Structure is every programmer’s best friend—and that applies to JavaScript, too.
If your project’s got more than about 100 lines of JavaScript, you should consider breaking it up. Group your code into files by “topic,” function, or objects (e.g. accounts, DOM, CreditCard, etc.). If you’ve got lots of those, further structure them in suitable directories.
Here’s an example from my app, Freckle (before and after):

A place for everything, and everything in its place. It’ll be easy to find the code you need.
| Pros | Cons |
|---|---|
| Easy to find code | A bazillion script tags |
| Easy to skim | Annoying to distribute |
| Easy to jump around your codebase | |
| Easier to grow |
As you can see, the benefits are many… and the downsides have to do only with the fact that, well, now you have a bunch of small files. It’s not fun maintaining a bevvy of script tags in your project.
The good news: This is a problem we can fix directly.
Breaking Up Ain’t Hard to Do: Tools
There are two approaches for solving the “too many script tags” problem:
- Client-side loading tools
- Server-side concatenation tools
Read on for the skinny on each approach, the best tools to use, indicators and counter-indicators.
Client-side loading tools
The approach: Use a library to load your JavaScript files for you. Declare which source files will be loaded, and in which order, using a nice JavaScript-based syntax (rather than copying & pasting script tags over and over).
The best tool: LAB.js. It loads your script files in parallel (while honoring dependencies), so it should offer improved performance over what its author calls “script tag soup.” And did I mention it’s prettier than script tag soup, too? And by far easier to maintain. (See that code sample below!)
When to use: If you absolutely can’t use a server-side tool, then you should use LAB.js. Or, if you’re deploying an app to an environment where speed is truly not an issue (e.g. an internal or local application, where everyone has super-high bandwidth and/or a short hop to the server).
Counter-indications: If your code uses document.write() or you use a framework with “unsafe DOM-ready detection.” Or if load-time performance is very important.
Sample code:
<script>
$LAB
.script("framework.js").wait()
.script("plugin.framework.js")
.script("myplugin.framework.js").wait()
.script("init.js");
</script>
Server-side concatenation tools
The approach: Create require()-type behavior in JavaScript. Have one master file that strings together (require()s) all the others, in order. Or even include snippets in the middle of other code, like inside objects. Use this to serve JavaScript as a single file (either on deploy, or by page request, with caching).
The best tool: Sprockets. Sprockets is a Ruby-based pre-processor that your deployment workflow will love. No deployment workflow? Sprockets also comes in other flavors: a Ruby on Rails plugin (official), and a couple PHP ports (unofficial), for concatenating on page request.
Bonus: use Sprockets to store just one copy of third-party code (like your fave library) on your computer, and reuse it in all your projects by “remote” inclusion. Finally, Sprockets can automatically minify and gzip your code after it does its concatenation thing.
When to use: You’ve got command-line fu, and especially if you already do have a deployment workflow (or deploy rarely). If you can use the Rails or PHP plugin for your dev time, or if you feel like porting its (simple, clear) functionality to your own language of choice. You need the absolute best loadtime performance.
Counter-indications: You don’t care about download performance, or it’s simply too aggravating to add Sprockets to your workflow for whatever reason. If you are allergic to Ruby (and PHP).
Sample code:
In your JavaScript:
// require 'myOtherJavaScript'
// require <prototype>
On the command-line:
$ sprocketize -I vendor/sprockets/prototype/src \
--asset-root=public \
app/javascripts/*.js > public/sprockets.js
This sample shows off the “reuse” of a single Prototype.js library, to boot.
Load or Concatenate: Which one’s for you?
Now you’ve got the run-down on both approaches, are you still unsure which is the right choice for you? Maybe this will help:
LAB.js is a serious effort and a very well-made tool, written by Kyle Simpson and Steve Souders. It offers performance improvement over multiple script tags, by loading JavaScript essentially “in the background” while the rest of the page continues to load. It’s great at what it does.
But no client-side loader can offer as much of a performance improvement as a server-side tool. No amount of parallelization can perform better than crushing all your JavaScript into a single file. (Especially once you minify it.) Sprockets has the advantage of having nothing else to maintain, to use its require() functionality. You can just slot in those require() statements where you need ’em.
Either way, however, the pay-off for a clean, compartmentalized code base is worth it… pardner.
Next week: How to use Sprockets. Subscribe so you don’t miss a thing!
Amy Hoy is the co-author of JavaScript Performance Rocks! (read the DailyJS review )—which has a lot more about Sprockets, and other speed-related topics—and a lover of all things JavaScript, as well as cowboy jokes.
JavaScript PDF Generation
I searched for JavaScript PDF generation just to see what server-side technologies are available. I found jsPDF, which works both server-side and in browser. It currently works best in Safari, Firefox 3+ and Opera.
It uses the data URI scheme to send the data to the browser, which is a problem for IE.
The code is easy to follow — if you want to learn about PDF generation it’s interesting to read through. There’s a demo page with usage examples and the resulting PDFs.
Usage looks like this:
var doc = new jsPDF();
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
doc.addPage();
doc.text(20, 20, 'Do you like that?');
// Output as Data URI
doc.output('datauri');
jsPDF doesn’t have many options yet — fonts are hardcoded for example (to helvetica). It’s an interesting demonstration of the power of client-side programming though.
Web Workers
When you’re writing JavaScript you typically think in single-threaded and event-based terms. This is fine for most tasks, and event-based programming is a great paradigm for classes of problems we face when writing JavaScript. However, not all problems are best modeled this way so sometimes we need threads.
The Web Workers Specification describes an API for running background scripts. Web Workers introduces the Worker constructor, and it looks like this:
var worker = new Worker('worker.js');
worker.onmessage = function(event) {
document.getElementById('result').textContent = event.data;
};
The onmessage handler allows your main script to receive messages from the worker. The worker is a separate script. This code will work in Firefox 3.5, Safari, and you can even emulate it using fakeworker.js.
Why?
Experienced JavaScript developers are so used to working without threads that they might question their validity. Well, traditional JavaScript is not parallel. Things that appear parallel are actually single-threaded, sharing execution with timers. This is a problem for long-running tasks: anything that will block on IO or intensive computation is a potential target for concurrency.
The necessity for threads will become more apparent as people write more sophisticated GUIs and games that use multimedia, especially if media needs to be decoded.
Runtime Implementation
How this is implemented by the runtime is completely dependent on the browser. The spec says:
Create a completely separate and parallel execution environment (i.e. a separate thread or process or equivalent construct), and run the rest of these steps asynchronously in that context.
And Mozilla’s implementation is encouraging:
The Worker interface spawns real OS-level threads… Read more in Using web workers
Each worker is run according to the run a worker algorithm.
Termination
Workers can be sent a terminate message to kill them using worker.terminate(). Workers will also be killed when browser windows are closed.
Shared Workers
Shared workers can be created using the SharedWorker constructor. Message ports are used to communicate with workers. The idea is that multiple pages can access the same worker pool.
A Fancy Example
I recently found this fancy Procedural Content Generator which is implemented using Worker(). It renders incredibly quickly in Safari.
Other Resources
John Resig has a post on Web Workers called Computing with JavaScript Web Workers which compares a benchmark against browsers before they had Web Worker.
CommonJS/JSGI: The Emerging JavaScript Application Server Platform covers how server-side JavaScript might adapt Web Workers, based on comments from the CommonJS wiki.
Computer Science in JavaScript
Computer Science in JavaScript is a set of classic computer science algorithms implemented in JavaScript. To download, use git:
git clone git://github.com/nzakas/computer-science-in-javascript.git
This will download a set of scripts that implement base64, linked lists, binary tree search, sorting, searching and checksums. These actually cover the first year of the computing degree that I studied — the basics of data structures, algorithms and encoding.
Of particular interest to coming of age JavaScript hackers will be the linked list implementations. The developer, Nicholas C. Zakas has even included unit tests (Written with YUI). The scripts include comments with explanations of the methods used, so it’s best to check out the code and read it if you want to explore this collection.
Tips and Links
I’ve got a bunch of JavaScript-related bookmarks to share. Things that don’t belong in a post by themselves, collected from reader comments and Twitter.
Unit Testing
Jakub Suder wrote a detailed article on JavaScript unit testing. This was found in a comment on my JavaScript Unit Testing article.
Learning Advanced JavaScript
The consensus seemed to be that David Flanagan’s Definitive Guide is one of the best books for studying JavaScript, according to comments on Learning Advanced JavaScript.
Firefox 3.6
Firefox 3.6 is out today. There’s a video overview here: What’s New in Firefox 3.6, and full release notes:
- Support for new DOM and HTML5 specifications including the Drag & Drop API and the File API
- Support for new CSS attributes such as gradients, background sizing, and pointer events
- Continued support for downloadable web fonts using the new WOFF font format
- The ability for web developers to indicate that scripts should run asynchronously to speed up page load times
Gordon
Everyone still seems fascinated with the JavaScript Flash renderer, Gordon. The GitHub repo now has over 1000 followers — it’s one of the most popular JavaScript projects on GitHub.
Atlas and Cappuccino
I wrote about Atlas in Atlas: Your First Tutorial. The beta programme is still rolling on, and it looks like Cappuccino is getting closer to version 0.8.
PostageApp
PostageApp is a bulk email service that targets web developers, and has a JSON-based API so it should be easy for JavaScript developers to use. I saw this in a tweet from dhh.
Thanks
We got some positive feedback on our JavaScript Performance Rocks! review. Thanks for the referrals, you’ll be handsomely rewarded with more articles!
JavaScript Speech Recognition
Elias sent us a link to his JavaScript speech recognition API at speechapi.com. It uses Flash to record audio and sends it to a server, then the server returns suggestions to a callback. You have to register to use the API. Using the API looks like this:
<script type="text/javascript" src="http://www.speechapi.com/speechle.js"></script>
<script language="JavaScript" type="text/javascript">
var speechle;
function TheSettings() {
var info = {'Userid':'eli', 'Logging':'true'};
var eventCallbacks={'OnResult':'result', 'OnLogging':'logging', 'OnFinishTTS':'finishTTS'};
var grammar={'Text':'one,two', 'Type':'simple'};
speechle = new SPEECHLE(info,eventCallbacks,grammar);
}
The site has a few demos. One which worked pretty reliably for me was the random quiz.
A similar technology is WAMI which uses Java instead. You can try a demo in the WAMI sandbox.
Standards
There are W3C standards relating to speech recognition:
- Speech Recognition Grammar Specification
- Voice Extensible Markup Language — a modular XML language for creating interactive media dialogs that feature synthesized speech, recognition of spoken and DTMF key input
See the Voice Browser Activity for a centralised pool of related W3C resources.
JavaScript Performance Rocks: Review
JavaScript Performance Rocks! is written by Amy Hoy & Thomas Fuchs (of Script.aculo.us fame). Since Jeff Bezos cited the link between page load times and Amazon’s sales performance, it seems like everyone wants to make faster pages. This book is a set of PDFs and bundled tools, benchmarks and demos to help you write faster JavaScript.

A copy of the book will set you back $39, and your company can buy a site license for 100 individuals for $249. Your $39 gets you:
- 4 PDFs, with diagrams and screenshots
- Benchmarks, exploring the performance of different language-oriented features and demonstrating how to compare algorithms
- Demos relating to the text
- The DOM Monster bookmarklet that helps analyse the DOM and other features of the page you’re on
- An example of how to use console.log
Book Structure
The book is split into 4 parts:
- Understanding and Measuring Performance (71 pages)
- Loadtime (74 pages)
- Runtime (110 pages)
- Interface Coping Strategies (27 pages)
Each of these parts is split into chapters. Chapters are usually bite-sized essays — 2-3 pages in size. Each part is 30-100 pages.
Understanding and Measuring Performance
This part introduces performance in the context of web apps. It helps you decide on how to strike the balance between things you can control, those you can’t, those that the business requires and those that your customers require. Here’s a choice quote:
Here you must rely on the inexact science of knowing how much crap people will take before they leave.
This sums up the tone of the book — it’s casual but without being inaccurate or annoying. The authors go on to explain the differences between the major versions of JavaScript, engines, and even includes benchmarks for major browsers, iPhone, Android and Palm Pre. This is where you can go to get a graph to explain to your boss or client why IE is such a problem!
The next chapter, Is Your App Behaving Badly? helps you determine if your app has performance issues. The Toolbox chapter explores tools like Firebug and YSlow, and even has some help for IE. The next chapter explains how to use the DOM Monster, and how to combine it with other tools. This chapter really helps to get to the heart of a lot of DOM-based performance issues — or at least understand why they’re happening.
There are also chapters on inspectors and how to use them for profiling. Safari’s Web Inspector and Firebug are used for detailed profiling examples.
The final chapters explain how to write your own benchmarking code, with common pitfalls and example code.
Loadtime
This part explains load order, caching and concatenation. Sprockets is used as an example of a tool that does concatenation. There’s also detailed coverage on how to set up Apache to cache properly, with solutions for gotchas like JSON and generated JavaScript.
The chapter on inlining is interesting. It explains when it’s safe to inline for performance reasons, and shows how to do it whilst retaining some level of sanity. It also talks about pre-caching — loading JavaScript and other resources while the user is doing something relatively slow (like filling out a form). Similarly, Chapter 9: Reduce Complexity gives strategies for reducing the overheads introduced by DOM elements and browser-based solutions.
Runtime
This part covers the really juicy stuff — the part that many of the readers of this blog would think of first when looking for a book about JavaScript performance. It covers everything from the use of operators and expression tuning, to run away timers and the advantages of JSON over XML.
This chapter includes many benchmarks and examples. Even basic statements are compared, like if vs. switch. Use of (function (){ })(); is explored, with performance and style notes. Even loop unrolling is covered, which is fairly low-level in terms of performance tuning but still useful.
There’s also a chapter on iPhone tips and tricks. This is useful if you’re a Cocoa iPhone developer and you use WebKit to wrap content or functionality, or if you’re a web developer targeting the iPhone browser.
UI Coping
This part gives advice on how to structure your app to perform well, even when technical fixes might not be possible. It gives overall architectural advice, and design techniques like progress bars and loading screens. This part is lighter on technical examples but has useful tips for getting JavaScript developers and designers to create something customers will enjoy to use.
Conclusion

This book is a treasure trove for web app developers. It covers the whole life-cycle: UI design, JavaScript performance, server-side and infrastructure issues. It’s written in a casual tone, and the authors make deeply technical aspects of JavaScript performance easy to understand.
If your web app is slow you’re going to love it — if you’re a hardcore JavaScript hacker exploring node.js and beyond it might not appeal as much (depending on the day job).
Disclaimer: We’ve got affiliate links for JavaScript Performance Rocks — although I bought my own copy with my hard-earned cash and I wouldn’t post a review of something that wasn’t worth buying! Buying a copy through the affiliate link will also help support DailyJS, which currently makes negative dollars.
jQuery 1.4 Released
Last week, version 1.4 of the popular jQuery library was released. The new version includes some big performance gains, alongside other cool stuff like:
- The ability to use .attr -style setter functions for all setters.
- Rails-style nested-parameter serialization for Ajax calls.
- Quick Element Construction: You can now pass in an object to add attributes and events at element-creation time:
jQuery("<div/>", { id: "foo", css: { height: "50px", width: "50px", color: "blue", backgroundColor: "#ccc" }, click: function() { $(this).css("backgroundColor", "red"); } }).appendTo("body");
- Per-property Easing: You can now specify easing for individual properties of an effect.
- The new jQuery.proxy method allows you to bind
thisinside an event-handler to a specific object. - You can now bind many events to an element by passing an object containing those events:
$("div.test").bind({ click: function(){ $(this).addClass("active"); }, mouseenter: function(){ $(this).addClass("inside"); }, mouseleave: function(){ $(this).removeClass("inside"); } });
- All events can now be .live events.
- Some new DOM-traversal, manipulation and utility functions have been introduced.
The 14 Days of jQuery website, created to celebrate the new release, covers what’s new in more detail.
Vienna.js
Thomas Fuchs has announced the first Vienna.js — a JavaScript meet up in Vienna, Austria on February 10, 2010, at Metalab.
They’ve got an official site at viennajs.org that features a fancy interactive JavaScript animation. They haven’t yet announced any talks but I’m sure they’ll attract some interesting folks.
Meanwhile there’s also a London JavaScript group on Meetup, with a meeting planned for January 21st. The group currently has 208 members so they may be able to pull something decent together.
Do you have a local JavaScript meet up? Are you planning any? Let me know in the comments!
JavaScript 3D: Pre3D

WebGL is coming, and is in fact already present in developer preview builds of Firefox, WebKit nightly and Chrome. Technically it’s possible to draw 3D graphics without WebGL. The Pre3d library by Dean McNamee does this, citing Kragen’s torus as inspiration.
It has a simple API, with syntax like this:
var path = new Pre3d.Path();
path.points = new Array(size);
path.curves = new Array(size);
Dean has some interesting comments in the source for pre3d.js with details on his design philosophy:
Because Arrays always go through the key lookup path, and there is no way to do a named lookup, it is faster to use objects than arrays for fixed size storage. You can think of this like the difference between a List and Tuple in languages like python
What about WebGL?
If you’re dying to start using WebGL now, I found an excellent blog called Learning WebGL. It has thorough lessons and a wiki.
Gordon: A Flash JavaScript Runtime
Gordon is a Flash JavaScript runtime written by Tobey Tailor. It currently supports the SWF 3 action model, which means it doesn’t yet support ActionScript Virtual Machine 2 (introduced by Flash 9). Tobey said a future version of Gordon will have ActionScript Virtual Machine 2 support (read more on Twitter: @tobeytailor).
Gordon parses the SWF file and then draws using SVG and JavaScript. It works well in Firefox and Safari, which also means it works on the iPhone.
There are some demos on paulirish.com/work/gordon/demos that illustrate SVG support and animation.
Usage looks like this:
new Gordon.Movie('trip.swf', {id: 'stage', width: 500, height: 400})
One thing I found interesting about Gordon is how it handles SWF file decoding. Tobey uses a zip library in inflate.js (written by Masanao Izumo) to decompress the file from a URL, then parse it.
Script Loading and Dependencies
I’ve created a few projects that are self-contained HTML/JavaScript files — small utilities that are easy to share or stash on a USB stick. When writing this type of project I like to use a script loader like Google’s AJAX Libraries so I don’t need to bundle separate files. Another use case is for very complex projects: Google’s API allows you to easily switch between different library versions which is great for testing against a new version of a big library like jQuery.
Dominoes
If you have a place to host code you might still want to use a script loader. I’ve recently been looking at javascript-dominoes which includes script loading, aliasing and dependencies. The dependency engine in particular allows you to express rules that permit scripts to be loaded concurrently, which could improve the load times of your pages.
The following examples are from the hands on documentation on the javascript-dominoes site.
Script Loading
Basic usage is like this:
dominoes("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" , function() {
// jQuery dependant code goes here
} );
If this is called twice dominoes will automatically detect that the script has already been loaded.
Substitution
Properties can be defined to shorten configuration:
dominoes.property("mySiteJSPath" , "http://mySite.org/u/kio/67/long/is/long/js");
dominoes("${mySiteJSPath}/script1.js" , function1);
Dependencies
If you have a script that does not depend on jQuery, you can tell dominoes to concurrently load the scripts:
dominoes("${jQueryURL} ./js/myScript/js" , myFunction);
Dependencies can be expressed using operators:
| action1 action2 | action1 & action2 are independant |
| action1 > action2 | action2 depends on the completion of action1 |
| action1 >| action2 | action2 depends on the completion of action1 and on the DOM being ready for manipulation |
| { sub-rule } | sub-rule (the completion of this action is determined by the completion of the whole sub-rule) |
{{ optional-sub-rule }} | optional sub-rule (same as a normal sub-rule but the completion of this action is not needed down the line, i.e. fire & forget) |



