Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Improve JSONP loading
- Make it asynchronous (append script to <head> rather than doing
  document.write)

- Scope callbacks under Jam.callbacks rather than polluting global
  namespace
  • Loading branch information
aanand committed Sep 4, 2012
1 parent 10bbf8a commit b7ed5f6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 14 deletions.
5 changes: 5 additions & 0 deletions index.html
Expand Up @@ -22,6 +22,11 @@
}

.jam-inactive a { color: gray; }

.jam-loading:after {
content: "Loading...";
color: gray;
}
</style>
</head>

Expand Down
34 changes: 20 additions & 14 deletions medallion.js
Expand Up @@ -8,6 +8,17 @@ Jam.escapeHTML = function(text) {
return tmpEl.innerHTML;
}

Jam.getJSONP = function (url, callback) {
var callbackName = '_'+Math.floor(Math.random()*1000000);

Jam.callbacks = Jam.callbacks || {};
Jam.callbacks[callbackName] = callback;

var script = document.createElement('script');
script.src = url + window.encodeURIComponent('Jam.callbacks.' + callbackName);
document.head.appendChild(script);
}

// Constructor

Jam.Medallion = function(options) {
Expand Down Expand Up @@ -48,20 +59,15 @@ Jam.Medallion.prototype.insertElement = function() {
};

Jam.Medallion.prototype.fetch = function(element) {
var callbackName = 'JamMedallionCallback_'+Math.floor(Math.random()*1000000);
var medallion = this;

window[callbackName] = function(json) {
medallion.setJSON(json);
medallion.render(json);
};

document.write(
'<script src="http://api.thisismyjam.com/1/' +
this.username +
'.json?callback=' +
callbackName +
'"></script>'
var medallion = this;

Jam.getJSONP(
'http://api.thisismyjam.com/1/' + this.username + '.json?callback=',

function(json) {
medallion.setJSON(json);
medallion.render();
}
);
};

Expand Down

0 comments on commit b7ed5f6

Please sign in to comment.