Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support JSONP callback #3

Open
brettz9 opened this issue May 26, 2017 · 0 comments
Open

Support JSONP callback #3

brettz9 opened this issue May 26, 2017 · 0 comments

Comments

@brettz9
Copy link

brettz9 commented May 26, 2017

Hi!

A nice simple but robust tool!

For JSONP, you might want to consider accepting a function as argument so that your script can define the function for the user. Besides this allowing for inline functions (or functions supplied as a variable name as opposed to string), your script could, if a callback name is not also supplied, set an auto-incrementing name for the function and append this name to the URL for the user (e.g., &callback=simpleLoadScript.jsonp123) assuming the server is configured to add dynamic callback names. Note that it can also be convenient to namespace the callbacks (on simpleLoadScript itself in this example), so new globals are not introduced, even temporarily.

In combination, this can avoid globals while allowing unnamed inline functions to be provided on the fly (and also de-uglify the supplied URL in avoiding manually setting its callback argument).

We use this approach at https://github.com/brettz9/jp/blob/master/index.js for our JSONP-only tool.

Alternatively, and in some ways I think even cooler though breaking prior compatibility, you could accept an API like this:

simpleLoadScript('://example.com', {callback: true}).then(function (callbackPayload) {});

This would make Promise.all more convenient, as it could allow JSONP to be retrieved concurrently with the results handled in one callback. The other disadvantage besides breaking compatibility is that you have to flag, e.g., with an argument as I did above, that this is JSONP.

Incidentally, I think you can avoid your all method by accepting an array for the url argument.

In combination, one could do this:

simpleLoadScript([
    '://example.com/path1',
    '://example.com/path2',
], {callback: true}).then(([callbackPayload1, callbackPayload2]) => {});

or if in an environment supporting await:

const [callbackPayload1, callbackPayload2] = await simpleLoadScript([
    '://example.com/path1',
    '://example.com/path2',
], {callback: true});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants