Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Code for "Things Which Aren't Magic - JSONP"
<!DOCTYPE html>
<head lang="en">
<meta charset="UTF-8">
<script type="text/javascript" src="jsonp.js"></script>
var addParagraph = function(text) {
var p = document.createElement('p');
p.textContent = text;
var API_URL = "";
JSONP.fetch(API_URL, function (res) {
res.items.forEach(function (item) {
var JSONP = function () {
return {
fetch: function (url, cb) {
// Generate a random function name
var cbName = "cb" + Math.floor(Math.random() * 1000);
// Define global callback function
window[cbName] = function(payload) {
// Call the users callback w/ payload
// Clean up this function when we're done;
delete window[cbName];
// Replace "callback=?" with actual callback function name
var scriptUrl = url.replace("callback=?", "callback=" + cbName);
// Inject script tag
var scriptElem = document.createElement("script");
scriptElem.setAttribute('src', scriptUrl);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.