Posts Tagged ‘afterOnLoad’

February 18th, 2009 6 Comments »
Tags: ,

Category: Tips

Inspecting JSON APIs with afterOnLoad

On page 22 of my book, I provided a sidebar called “Injecting Dojo” in which I provided a hack for inserting Dojo into the page after onload (or equivalent) handlers have fired via dynamic SCRIPT tag insertion. The problem was that as of version 1.1, there wasn’t a good way to fire an addOnLoad handler after Dojo was ready, so the possibilities were a bit limited.

As of version 1.2, however, Dojo added full support for a configuration switch called afterOnLoad as well as the ability to pass in an addOnLoad handler right into djConfig. In combination, you get a nice, clean way to get Dojo running in the page after it’s already been loaded, whether it is via a bookmarklet or some other scenarios such as lazy-loading.

To demonstrate the utility of these features with a simple illustration, consider a scenario in which you’re debugging or inspecting a JSON API, and you’d like to reformat the output that appears in the browsers to be pretty-printed instead of all one one long line, so that it’s easier to read. You could install this snippet as a bookmarklet (by dragging and dropping that link into your browser’s toolbar for most browsers, or right clicking and saving it in IE) to get the job done:

(function() {
    afterOnLoad: true,
    addOnLoad: function() {
      var _json = dojo.fromJson(dojo.body().innerHTML);
      dojo.body().innerHTML= "<html><body><pre>"+
      dojo.toJson(_json, true /* pretty print*/)+
  var e=document.createElement("script");

As you can well infer, the script is simply taking the body of the page and rewriting it as nicely-formatted JSON. It’s not hard to imagine baking in a little regex that scrapes off the “padding” part of a JSON-P API if you needed that kind of support.