Getting d3 to work for Local Files

d3 is an incredibly slick javascript charting/graphing library by Michael Bostock.

When running examples locally, you might notice that some of them don't work using the latest version of d3 (as of May 24, 2012).  This is due to the way the ajax calls are working when called against the local file system.  It turns out that this can be addressed (for firefox and safari) by tweaking the d3 code with a one line change.  After I realized that this made thing work (yeah), I saw that this change is currently a recent pending pull request from Jason Davies for the git-hosted project

Basically, in function d3.xhr at about line 497 of d3.v2.js, you change this line

callback(s >= 200 && s < 300 || s === 304 ? req : null);

to this:

callback(!s && req.response || s >= 200 && s < 300 || s === 304 ? req : null);

What's going on is that when an ajax call is run against a local file, the status will be 0, even though it was able to grab the contents of the file (for firefox and safari, at least). 

Being able to run things locally makes for being able to develop slick offline web apps with d3. However, note that other browsers may handle this differently, as there are security implications.

Popular Posts