Created
June 17, 2015 21:11
-
-
Save developit/de9f35cdf98a6fae5dd6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* var jpr = new JSONPRequest(); | |
* jpr.onload = (...data) => { | |
* console.log(data); | |
* }; | |
* jpr.open('GET', 'some-url?callback={{callback}}'); | |
* jpr.send(); | |
*/ | |
export class JSONPRequest { | |
constructor(url) { | |
this.id = ++JSONPRequest.COUNT; | |
this.script = document.createElement('script'); | |
this.script.setAttribute('data-request-id', id); | |
if (url) this.open('GET', url); | |
this._cb = `jsonpcb${id}`; | |
window[this._cb] = (...args) => this._load(...args); | |
} | |
open(method, url) { | |
this.url = url || method; | |
this.script.src = this.url.replace(/\{\{?callback\}?\}/g, this._cb); | |
this.script.src = this.url; | |
} | |
send() { | |
(document.head || document.getElementsByTagName('head')[0]).appendChild(this.script); | |
} | |
cancel() { | |
this.cancelled = true; | |
this.script.parentNode.removeChild(this.script); | |
}, | |
_load(...args) { | |
if (!this.cancelled && typeof this.onload==='function') { | |
this.onload(...args); | |
} | |
} | |
} | |
JSONPRequest.COUNT = 0; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment