Skip to content

Commit

Permalink
Import final version of the 0.1.0 files
Browse files Browse the repository at this point in the history
Everything should be working at this point; there's a build script
for generating the /dist/ directory, unit tests (both browser-based
and command-line) and some basic documentation (README.md).
  • Loading branch information
jeffreybarke committed Aug 10, 2015
1 parent 6ac4d87 commit 4c6405e
Show file tree
Hide file tree
Showing 12 changed files with 502 additions and 70 deletions.
22 changes: 15 additions & 7 deletions Gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module.exports = function(grunt) {

build: {
// Build time
time: grunt.template.today('mmmm d, yyyy hh:MM:ss TT'),
time: grunt.template.today('d mmm yyyy hh:MM:ss TT'),
// Build version
version: '<%= pkg.version %>',
// Build file names
Expand All @@ -25,12 +25,13 @@ module.exports = function(grunt) {

copy: {
dist: {
files: [
{
src: '<%= build.paths.src %>/<%= build.fileNames.src %>',
dest: '<%= build.paths.dest %>/<%= build.fileNames.src %>'
options: {
process: function(content) {
return grunt.template.process(content);
}
]
},
src: '<%= build.paths.src %>/<%= build.fileNames.src %>',
dest: '<%= build.paths.dest %>/<%= build.fileNames.src %>'
}
},

Expand Down Expand Up @@ -62,7 +63,14 @@ module.exports = function(grunt) {
drop_console: true
},
mangle: true,
preserveComments: 'some',
preserveComments: false,
banner: '/*! jsonp.js v<%= build.version %>: A lightweight ' +
'JSONP library.\n' +
' * Copyright 2015 Jeffrey Barke. Released under the MIT ' +
'license\n' +
' * <https://github.com/jeffreybarke/jsonp> . ' +
'<%= build.time %>\n' +
' */\n',
sourceMap: false
},
js : {
Expand Down
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# jsonp.js: A lightweight JSONP library

jsonp.js is a lightweight JSONP library for situations where CORS is not an option and jQuery is too heavy. jsonp.js is approximately one KB minified, only makes JSONP requests and should have a somewhat familiar (jQuery-like) syntax.

Tested in Chrome 43.0.x, Firefox 32.0.3 and IE 8 and 10 on Windows 7 SP 1; IE 7 on Windows Vista SP 2; and Chrome 44.0.x, Firefox 39.0.3 and Safari 6.2.7 on a Mac 10.8.5.

## Usage

Grab the latest minified version of `jsonp.js` from the `dist` directory of this repo and add a script element referencing it.

After it's been referenced, make a call to:
`jsonp(url [, settings]);` per below.

### jsonp(url [, settings]);

* __url__ (_String_): A string containing the URL to which the request is sent.
* __settings__ (_Object_): A set of key/value pairs that configure the JSONP request (see below for a complete list). All settings are optional if the `url` is passed.

### jsonp([settings]);

A set of key/value pairs that configure the JSONP request. All settings are optional except the `url` key/value pair, which is required.

* __cache__ (_Boolean_): Defaults to `false`. If set to `false`, it will force requested pages not to be cached by the browser. It works by appending "_={timestamp}" to the GET parameters. Note that to enable caching, it is not enough to set this parameter to `true`. You'll also need to set the `callbackName`.
* __callbackName__ (_String_): Specify the callback function name for the JSONP request. This value will be used instead of the random name automatically generated by jsonp.js. It is preferable to let jsonp.js generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. However, you may want to specify the callback when you want to enable better browser caching (`cache: true`). The `callbackName` parameter is the the "?" in the `callback=?` part of the query string in the URL.
* __callbackParam__ (_String_): Override the callback function name for the remote request. This value will be used instead of "callback" in the `callback=?` part of the query string in the URL.
* __complete__ (_Function_): A function to be called when the request finishes (after `success` and `error` callbacks are executed). This function will be passed any data passed to the `success` function or nothing if the `error` callback was executed.
* __context__ (_Object_): This objet will be the context of all JSONP-related callbacks (what the `this` will point to). By default, the context is the `window` object.
* __error__ (_Function_): A function to be executed if the request fails. __Note:__ This handler will _only_ be called if a `timeout` is specified and then exceeded. It will _not_ be called for `400` or `500` server responses.
* __success__ (_Function_): A function to be called if the request succeeds. The function will be passed a JSON data object.
* __timeout__ (_Number_): Set a timeout (in milliseconds) for the request. If a JSONP request times out, it will execute the `error` callback. Note--this is the only way the `error` callback will be executed.
* __url__ (_String_): A string containing the URL to which the request is sent.

## Contributing

Please let me know of any [bugs](https://github.com/jeffreybarke/jsonp/labels/bug) or [feature requests](https://github.com/jeffreybarke/jsonp/labels/enhancement).

Otherwise, fork the repo, clone locally and run `npm install` to install the dependencies.

Unit tests can be ran with:
`grunt test`

The `/dist/` directory can be updated with:
`grunt build`

## License

jsonp.js is available under the [MIT license](LICENSE).
144 changes: 144 additions & 0 deletions dist/jsonp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/*! jsonp.js v0.1.0: A lightweight JSONP library.
* Copyright 2015 Jeffrey Barke. Released under the MIT license
* <https://github.com/jeffreybarke/jsonp> . 9 Aug 2015 10:57:23 PM
*/
(function(window, undefined) {
'use strict';

var document = window.document,
// Hoisting:
cleanUp,
Jsonp,
jsonp;

// Polyfill Date.now:
if (!Date.now) {
Date.now = function() {
return new Date().getTime();
};
}

// Jsonp private utility function

cleanUp = function cleanUp(head, script, callback) {
// Remove the script element from the head element.
head.removeChild(script);
// Remove the callback.
if (this[callback]) {
delete this[callback];
}
};

/**
* Jsonp constructor function
*/
Jsonp = function JsonP(url, opts) {
// Set the opts.
if (typeof url === 'object') {
// Only passed an object.
opts = url;
this.url = opts.url;
} else {
// Passed a string url and an opts object.
opts = opts || {};
this.url = url;
}
this.cache = opts.cache || false;
this.callbackName = opts.callbackName || false;
this.callbackParam = opts.callbackParam || false;
this.complete = opts.complete || false;
this.context = opts.context || false;
this.error = opts.error || false;
this.success = opts.success || false;
this.timeout = opts.timeout || false;
// If we have a URL, make the call, otherwise, not.
// Can always manually set the instance.url and call instance.load().
if (this.url) {
this.load();
}
return this;
};

// Need a static counter for all Jsonp instances, because if it happens
// fast enough, the timestamp isn't enough to uniquely identify
// the callback name in the load function below.
Jsonp.counter = 1;

Jsonp.prototype.load = function load() {
var url = this.url,
ts = Date.now(),
callback = this.callbackName || 'cb' + ts + Jsonp.counter,
script = document.createElement('script'),
id = 'script' + ts + Jsonp.counter,
head = document.documentElement.firstChild,
timeout = this.timeout,
self = this;
// Always increment counter.
Jsonp.counter += 1;
// The one thing we really need, a URL.
// @TODO: Throw an exception? console.log or something else?
if (!url) {
return false;
}
// Get the URL ready to take some querystring parameters
if (url.indexOf('?') !== -1) {
url += '&';
} else {
url += '?';
}
// If we're not caching the request, add a timestap
if (this.cache === false) {
url += '_=' + ts + '&';
}
// Add the callback parameter:
url += (this.callbackParam ? this.callbackParam : 'callback') +
'=' + callback;
// Create a callback that will call the user-passed callbacks
// @TODO: Should use bind, but for maximum compatibility, using "self"
window[callback] = function(data) {
var context = self.context || window;
if (self.success) {
self.success.call(context, data);
}
if (self.complete) {
self.complete.call(context, data);
}
};
// Set the script attributes.
script.setAttribute('id', id);
script.setAttribute('src', url);
// On script load, clean up.
script.onload = function() {
cleanUp.call(window, head, script, callback);
};
// Add the script to the page.
head.appendChild(script);
// Check to see if we have a timeout; if so cleanup.
// If there's an error callback, call that as well.
if (timeout) {
window.setTimeout(function() {
var el = document.getElementById(id);
// Element should have loaded and cleared itself; do it manually.
if (el) {
cleanUp.call(window, head, el, callback);
if (self.error) {
self.error.call(self.context || window);
}
}
}, timeout);
}
};

/**
* jsonp utility function to "wrap" the Jsonp constructor function.
* This way client code won't need to use the "new" operator with
* Jsonp. Necessary, not really? Convenient? Debatable.
*/
jsonp = function jsonp(url, opts) {
return new Jsonp(url, opts);
};

// Export the jsonp object for <script> tags.
window.jsonp = jsonp;

}(this));
5 changes: 5 additions & 0 deletions dist/jsonp.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 4c6405e

Please sign in to comment.