How to provide callback function to iTunes search API - javascript

I am struggling to find a way to provide a callback function to correctly use the iTunes Store search API.
I am trying to achieve this behaviour:
const getiTunes = fetch(`https://itunes.apple.com/search?term=${search}&media=movie&limit=200`)
.then(results => results.json())
.then(results => {
if (results.errorMessage) throw Error(results.errorMessage)
else setResults(results)
})
.catch(error => {
//handle error
})
and so far I have this:
const getiTunes = results => {
if (results.errorMessage) throw Error(results.errorMessage)
else setITunes(results)
}
const script = document.createElement("script")
script.src = `https://itunes.apple.com/search?term=${search}&media=movie&limit=200&callback=getiTunes`
script.async = true
document.body.appendChild(script)
I keep getting the following error:
Uncaught ReferenceError: getiTunes is not defined
I have also tried &callback="getiTunes" and &callback=${getiTunes} and they also fail.
These functions are being called in an useEffect hook in React. Is there a specific way I have to retrieve the function name?
Aside
And if I try to not provide a callback function, it will work only if the search is a new search (ie I haven't searched that term before). However, if I have (say on production URL or locally) then it will error with the following:
Access to fetch at 'https://itunes.apple.com/search?term=spiderman&media=movie&limit=200' from origin 'http://localhost:3000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value "--it has the last URL I used to search for this successfully--"...

The method you're trying is JSONP (JSON with Padding) method. We just need the external script and the a function.
The external website provides a callback function for your method.
So it sends all the data in function parameter.
by mistaken you have adden } to your script url
script.src = `https://itunes.apple.com/search?term=${search}&media=movie&limit=200&callback=getiTunes}`
Eg code:
const getiTunes=results=>{
if (results.errorMessage) throw new
Error(results.errorMessage)
else setITunes(results)
};
const script = document.createElement("script")
script.src = `https://itunes.apple.com/search?term=bat&media=movie&limit=200&callback=getiTunes`
script.async = true
document.body.appendChild(script);
// returns getiTunes(...someData)

I was able to get this working by adding my script to handle the response to the document also.
const loadItunes = document.createElement("script")
loadItunes.src = `https://itunes.apple.com/search?term=${search}&media=movie&limit=200&callback=getiTunes`
loadItunes.async = true
const handleResults = document.createElement("script")
handleResults.type = "text/javascript"
handleResults.text = "function getiTunes(response) { //function code };"
document.body.appendChild(loadItunes)
document.body.appendChild(handleResults)
Updated Answer
I have found a better solution via this code sandbox. It perfectly solves this problem by creating a function which then hands off the response to a callback function.
export const fetchJSONP = (url, callback) => {
var callbackName = "jsonp_callback_" + Math.round(100000 * Math.random())
window[callbackName] = function (data) {
delete window[callbackName]
document.body.removeChild(script)
callback(data)
}
var script = document.createElement("script")
script.src = url + (url.indexOf("?") >= 0 ? "&" : "?") + "callback=" + callbackName
document.body.appendChild(script)
}
I then use it in the following way:
const handleResponse = response => {
//do stuff with response
}
fetchJSONP("https://itunes.apple.com/search?term=spiderman&media=movie&limit=200", handleResponse)

Related

handle unnamed JSONP in xmlHttpRequest Javascript [duplicate]

Can I make a cross-domain JSONP request in JavaScript without using jQuery or other external library? I would like to use JavaScript itself and then parse the data and make it an object so I could use it. Do I have to use an external library? If not, how can I do it?
function foo(data)
{
// do stuff with JSON
}
var script = document.createElement('script');
script.src = '//example.com/path/to/jsonp?callback=foo'
document.getElementsByTagName('head')[0].appendChild(script);
// or document.head.appendChild(script) in modern browsers
Lightweight example (with support for onSuccess and onTimeout). You need to pass callback name within URL if you need it.
var $jsonp = (function(){
var that = {};
that.send = function(src, options) {
var callback_name = options.callbackName || 'callback',
on_success = options.onSuccess || function(){},
on_timeout = options.onTimeout || function(){},
timeout = options.timeout || 10; // sec
var timeout_trigger = window.setTimeout(function(){
window[callback_name] = function(){};
on_timeout();
}, timeout * 1000);
window[callback_name] = function(data){
window.clearTimeout(timeout_trigger);
on_success(data);
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);
}
return that;
})();
Sample usage:
$jsonp.send('some_url?callback=handleStuff', {
callbackName: 'handleStuff',
onSuccess: function(json){
console.log('success!', json);
},
onTimeout: function(){
console.log('timeout!');
},
timeout: 5
});
At GitHub: https://github.com/sobstel/jsonp.js/blob/master/jsonp.js
What is JSONP?
The important thing to remember with jsonp is that it isn't actually a protocol or data type. Its just a way of loading a script on the fly and processing the script that is introduced to the page. In the spirit of JSONP, this means introducing a new javascript object from the server into the client application/ script.
When is JSONP needed?
It is 1 method of allowing one domain to access/ process data from another in the same page asyncronously. Primarily, it is used to override CORS (Cross Origin Resource Sharing) restrictions which would occur with an XHR (ajax) request. Script loads are not subject to CORS restrictions.
How is it done
Introducing a new javascript object from the server can be implemented in many ways, but the most common practice is for the server to implement the execution of a 'callback' function, with the required object passed into it. The callback function is just a function you have already set up on the client which the script you load calls at the point the script loads to process the data passed in to it.
Example:
I have an application which logs all items in someone's home. My application is set up and I now want to retrieve all the items in the main bedroom.
My application is on app.home.com. The apis I need to load data from are on api.home.com.
Unless the server is explicitly set up to allow it, I cannot use ajax to load this data, as even pages on separate subdomains are subject to XHR CORS restrictions.
Ideally, set things up to allow x-domain XHR
Ideally, since the api and app are on the same domain, I might have access to set up the headers on api.home.com. If I do, I can add an Access-Control-Allow-Origin: header item granting access to app.home.com. Assuming the header is set up as follows: Access-Control-Allow-Origin: "http://app.home.com", this is far more secure than setting up JSONP. This is because app.home.com can get everything it wants from api.home.com without api.home.com giving CORS access to the whole internet.
The above XHR solution isn't possible. Set up JSONP On my client script: I set up a function to process the reponse from the server when I make the JSONP call.:
function processJSONPResponse(data) {
var dataFromServer = data;
}
The server will need to be set up to return a mini script looking something like "processJSONPResponse('{"room":"main bedroom","items":["bed","chest of drawers"]}');" It might be designed to return such a string if something like //api.home.com?getdata=room&room=main_bedroom is called.
Then the client sets up a script tag as such:
var script = document.createElement('script');
script.src = '//api.home.com?getdata=room&room=main_bedroom';
document.querySelector('head').appendChild(script);
This loads the script and immediately calls window.processJSONPResponse() as written/ echo/ printed out by the server. The data passed in as the parameter to the function is now stored in the dataFromServer local variable and you can do with it whatever you need.
Clean up
Once the client has the data, ie. immediately after the script is added to the DOM, the script element can be removed from the DOM:
script.parentNode.removeChild(script);
My understanding is that you actually use script tags with JSONP, sooo...
The first step is to create your function that will handle the JSON:
function hooray(json) {
// dealin wit teh jsonz
}
Make sure that this function is accessible on a global level.
Next, add a script element to the DOM:
var script = document.createElement('script');
script.src = 'http://domain.com/?function=hooray';
document.body.appendChild(script);
The script will load the JavaScript that the API provider builds, and execute it.
the way I use jsonp like below:
function jsonp(uri) {
return new Promise(function(resolve, reject) {
var id = '_' + Math.round(10000 * Math.random());
var callbackName = 'jsonp_callback_' + id;
window[callbackName] = function(data) {
delete window[callbackName];
var ele = document.getElementById(id);
ele.parentNode.removeChild(ele);
resolve(data);
}
var src = uri + '&callback=' + callbackName;
var script = document.createElement('script');
script.src = src;
script.id = id;
script.addEventListener('error', reject);
(document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script)
});
}
then use 'jsonp' method like this:
jsonp('http://xxx/cors').then(function(data){
console.log(data);
});
reference:
JavaScript XMLHttpRequest using JsonP
http://www.w3ctech.com/topic/721 (talk about the way of use Promise)
I have a pure javascript library to do that https://github.com/robertodecurnex/J50Npi/blob/master/J50Npi.js
Take a look at it and let me know if you need any help using or understanding the code.
Btw, you have simple usage example here: http://robertodecurnex.github.com/J50Npi/
/**
* Loads data asynchronously via JSONP.
*/
const load = (() => {
let index = 0;
const timeout = 5000;
return url => new Promise((resolve, reject) => {
const callback = '__callback' + index++;
const timeoutID = window.setTimeout(() => {
reject(new Error('Request timeout.'));
}, timeout);
window[callback] = response => {
window.clearTimeout(timeoutID);
resolve(response.data);
};
const script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = url + (url.indexOf('?') === -1 ? '?' : '&') + 'callback=' + callback;
document.getElementsByTagName('head')[0].appendChild(script);
});
})();
Usage sample:
const data = await load('http://api.github.com/orgs/kriasoft');
I wrote a library to handle this, as simply as possible. No need to make it external, its just one function. Unlike some other options, this script cleans up after itself, and is generalized for making further requests at runtime.
https://github.com/Fresheyeball/micro-jsonp
function jsonp(url, key, callback) {
var appendParam = function(url, key, param){
return url
+ (url.indexOf("?") > 0 ? "&" : "?")
+ key + "=" + param;
},
createScript = function(url, callback){
var doc = document,
head = doc.head,
script = doc.createElement("script");
script
.setAttribute("src", url);
head
.appendChild(script);
callback(function(){
setTimeout(function(){
head
.removeChild(script);
}, 0);
});
},
q =
"q" + Math.round(Math.random() * Date.now());
createScript(
appendParam(url, key, q), function(remove){
window[q] =
function(json){
window[q] = undefined;
remove();
callback(json);
};
});
}
Please find below JavaScript example to make a JSONP call without JQuery:
Also, you can refer my GitHub repository for reference.
https://github.com/shedagemayur/JavaScriptCode/tree/master/jsonp
window.onload = function(){
var callbackMethod = 'callback_' + new Date().getTime();
var script = document.createElement('script');
script.src = 'https://jsonplaceholder.typicode.com/users/1?callback='+callbackMethod;
document.body.appendChild(script);
window[callbackMethod] = function(data){
delete window[callbackMethod];
document.body.removeChild(script);
console.log(data);
}
}
/**
* Get JSONP data for cross-domain AJAX requests
* #private
* #link http://cameronspear.com/blog/exactly-what-is-jsonp/
* #param {String} url The URL of the JSON request
* #param {String} callback The name of the callback to run on load
*/
var loadJSONP = function ( url, callback ) {
// Create script with url and callback (if specified)
var ref = window.document.getElementsByTagName( 'script' )[ 0 ];
var script = window.document.createElement( 'script' );
script.src = url + (url.indexOf( '?' ) + 1 ? '&' : '?') + 'callback=' + callback;
// Insert script tag into the DOM (append to <head>)
ref.parentNode.insertBefore( script, ref );
// After the script is loaded (and executed), remove it
script.onload = function () {
this.remove();
};
};
/**
* Example
*/
// Function to run on success
var logAPI = function ( data ) {
console.log( data );
}
// Run request
loadJSONP( 'http://api.petfinder.com/shelter.getPets?format=json&key=12345&shelter=AA11', 'logAPI' );
If you are using ES6 with NPM, you can try node module "fetch-jsonp".
Fetch API Provides support for making a JsonP call as a regular XHR call.
Prerequisite:
you should be using isomorphic-fetch node module in your stack.
Just pasting an ES6 version of sobstel's nice answer:
send(someUrl + 'error?d=' + encodeURI(JSON.stringify(json)) + '&callback=c', 'c', 5)
.then((json) => console.log(json))
.catch((err) => console.log(err))
function send(url, callback, timeout) {
return new Promise((resolve, reject) => {
let script = document.createElement('script')
let timeout_trigger = window.setTimeout(() => {
window[callback] = () => {}
script.parentNode.removeChild(script)
reject('No response')
}, timeout * 1000)
window[callback] = (data) => {
window.clearTimeout(timeout_trigger)
script.parentNode.removeChild(script)
resolve(data)
}
script.type = 'text/javascript'
script.async = true
script.src = url
document.getElementsByTagName('head')[0].appendChild(script)
})
}

Javascript JsonP syntax error when using previous example

This is a follow up to this question:
JavaScript XMLHttpRequest using JsonP
I was trying to experiment with JsonP, since I'm trying to find a replacement for using a Cors proxy. I tried the example listed in the 2nd answer of the linked question but I got this error:
SyntaxError: expected expression, got '<'[Learn More] www.google.com:1
Why is that?
The code used:
function jsonp(url) {
return new Promise(function(resolve, reject) {
let script = document.createElement('script')
const name = "_jsonp_" + Math.round(100000 * Math.random());
//url formatting
if (url.match(/\?/)) url += "&callback="+name
else url += "?callback="+name
script.src = url;
window[name] = function(data) {
resolve(data);
document.body.removeChild(script);
delete window[name];
}
document.body.appendChild(script);
});
}
var data = jsonp("https://www.google.com");
data.then((res) => {
console.log(res);
});

How to get the status code for dynamically created script tag?

My code dynamically creates a <script> tag and attached it to the DOM tree. However, if for some reason the script fails to load, I need to figure out why. The event object passed to onerror callback does not show any information about why the script fails to load. I would like to at least get the status code of the request so I can determine if that's a 404 or 500. Is this possible?
In this question someone says that it is not possible to get the status code for <img> tag. I'm wondering if that also true for <script> tag.
According to XML.com,
The most notable downside [of the script tag] is that it cannot handle errors gracefully. If the web service returns an invalid JavaScript statement to the script tag, a JavaScript error will be generated. If the web service returns invalid JSON wrapped inside a callback function, a JavaScript error will be returned when the invalid JSON data is passed to the callback function. If your web service returns an HTTP return code other than 200 (successful), then the script tag will silently fail.
So no, there is no way to determine a non-200 status code of a dynamic <script> tag.
Having said that, if you use an AJAX request, you will be able to get both the status code and error:
You can try to fetch the script first and catch all errors information
If fetch success u can load the script from the blob.
U can find my full solution here
const loadScriptWithFetchFirst = function (url, includeCrossOrigin = true) {
return new Promise(function (resolve, reject) {
fetch(url,{ mode: includeCrossOrigin ? 'cors' : 'no-cors'})
.then((response) => {
if (!response.ok) {
reject(`Can't load script ${url} error: ${response.status}; ${response.statusText}`);
return null;
}
else {
return response.blob()}
})
.then((blob) => {
if (blob !== null) {
return;
}
const objectURL = URL.createObjectURL(blob);
const script = document.createElement('script');
script.src = objectURL;
if (includeCrossOrigin) {
script.crossOrigin = 'anonymous';
}
script.onload = function () {
resolve(true);
}
script.onerror = function (event) {
reject(event ? event : '')
};
document.head.appendChild(script);
})
.catch((e)=>{
reject(`Request failed: ${e}`);
})
});
};

Firefox add-on get the DOM window which made an HTTP request

I'm capturing the HTTP requests in a Firefox Add-on SDK extension. I need to get the DOM window associated with the request. However, I'm getting an NS_NOINTERFACE error.
Here is my code:
var httpRequestObserver = {
observe: function (subject, topic, data) {
var httpRequest = subject.QueryInterface(Ci.nsIHttpChannel);
var requestUrl = subject.URI.host;
var domWin;
var assWindow;
console.log('URL: ', requestUrl);
try {
domWin = httpRequest.notificationCallbacks.getInterface(Ci.nsIDOMWindow);
assWindow = httpChannel.notificationCallbacks.getInterface(Ci.nsILoadContext)
.associatedWindow;
console.log(domWin);
} catch (e) {
console.log(e);
}
// console.log('TAB: ', tabsLib.getTabForWindow(domWin.top));
var hostName = wn.domWindow.getBrowser().selectedBrowser.contentWindow.location.host;
console.log('HOST: ', hostName);
},
get observerService() {
return Cc['#mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
},
register: function () {
this.observerService.addObserver(this, 'http-on-modify-request', false);
},
unregister: function () {
this.observerService.removeObserver(this, 'http-on-modify-request');
}
};
httpRequestObserver.register();
I've tried both nsIDOMWindow and nsILoadContext, but NS_NOINTERFACE error always appears on an attempt to get the window object.
I have finally managed to get the data I need via
httpRequest.notificationCallbacks.getInterface(Ci.nsILoadContext).topFrameElement
For example, to get url of the document which started the request, I used
httpRequest.notificationCallbacks.getInterface(Ci.nsILoadContext).topFrameElement._documentURI.href
Since you already found how to get the <browser> from the request you can do the following to get back to SDK APIs:
let browser = ....topFrameElement
let xulTab = browser.ownerDocument.defaultView.gBrowser.getTabForBrowser(browser)
let sdkTab = modelFor(xulTab)
modelFor() is documented in the tabs module.

jQuery.getScript alternative in native JavaScript

I'm trying to load JS scripts dynamically, but using jQuery is not an option.
I checked jQuery source to see how getScript was implemented so that I could use that approach to load scripts using native JS. However, getScript only calls jQuery.get()
and I haven't been able to find where the get method is implemented.
So my question is,
What's a reliable way to implement my own getScript method using native JavaScript?
Thanks!
Here's a jQuery getScript alternative with callback functionality:
function getScript(source, callback) {
var script = document.createElement('script');
var prior = document.getElementsByTagName('script')[0];
script.async = 1;
script.onload = script.onreadystatechange = function( _, isAbort ) {
if(isAbort || !script.readyState || /loaded|complete/.test(script.readyState) ) {
script.onload = script.onreadystatechange = null;
script = undefined;
if(!isAbort && callback) setTimeout(callback, 0);
}
};
script.src = source;
prior.parentNode.insertBefore(script, prior);
}
You can fetch scripts like this:
(function(document, tag) {
var scriptTag = document.createElement(tag), // create a script tag
firstScriptTag = document.getElementsByTagName(tag)[0]; // find the first script tag in the document
scriptTag.src = 'your-script.js'; // set the source of the script to your script
firstScriptTag.parentNode.insertBefore(scriptTag, firstScriptTag); // append the script to the DOM
}(document, 'script'));
use this
var js_script = document.createElement('script');
js_script.type = "text/javascript";
js_script.src = "http://www.example.com/script.js";
js_script.async = true;
document.getElementsByTagName('head')[0].appendChild(js_script);
Firstly, Thanks for #Mahn's answer. I rewrote his solution in ES6 and promise, in case someone need it, I will just paste my code here:
const loadScript = (source, beforeEl, async = true, defer = true) => {
return new Promise((resolve, reject) => {
let script = document.createElement('script');
const prior = beforeEl || document.getElementsByTagName('script')[0];
script.async = async;
script.defer = defer;
function onloadHander(_, isAbort) {
if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) {
script.onload = null;
script.onreadystatechange = null;
script = undefined;
if (isAbort) { reject(); } else { resolve(); }
}
}
script.onload = onloadHander;
script.onreadystatechange = onloadHander;
script.src = source;
prior.parentNode.insertBefore(script, prior);
});
}
Usage:
const scriptUrl = 'https://www.google.com/recaptcha/api.js?onload=onRecaptchaLoad&render=explicit';
loadScript(scriptUrl).then(() => {
console.log('script loaded');
}, () => {
console.log('fail to load script');
});
and code is eslinted.
This polishes up previous ES6 solutions and will work in all modern browsers
Load and Get Script as a Promise
const getScript = url => new Promise((resolve, reject) => {
const script = document.createElement('script')
script.src = url
script.async = true
script.onerror = reject
script.onload = script.onreadystatechange = function() {
const loadState = this.readyState
if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
script.onload = script.onreadystatechange = null
resolve()
}
document.head.appendChild(script)
})
Usage
getScript('https://dummyjs.com/js')
.then(() => {
console.log('Loaded', dummy.text())
})
.catch(() => {
console.error('Could not load script')
})
Also works for JSONP endpoints
const callbackName = `_${Date.now()}`
getScript('http://example.com/jsonp?callback=' + callbackName)
.then(() => {
const data = window[callbackName];
console.log('Loaded', data)
})
Also, please be careful with some of the AJAX solutions listed as they are bound to the CORS policy in modern browsers https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
There are some good solutions here but many are outdated. There is a good one by #Mahn but as stated in a comment it is not exactly a replacement for $.getScript() as the callback does not receive data. I had already written my own function for a replacement for $.get() and landed here when I need it to work for a script. I was able to use #Mahn's solution and modify it a bit along with my current $.get() replacement and come up with something that works well and is simple to implement.
function pullScript(url, callback){
pull(url, function loadReturn(data, status, xhr){
//If call returned with a good status
if(status == 200){
var script = document.createElement('script');
//Instead of setting .src set .innerHTML
script.innerHTML = data;
document.querySelector('head').appendChild(script);
}
if(typeof callback != 'undefined'){
//If callback was given skip an execution frame and run callback passing relevant arguments
setTimeout(function runCallback(){callback(data, status, xhr)}, 0);
}
});
}
function pull(url, callback, method = 'GET', async = true) {
//Make sure we have a good method to run
method = method.toUpperCase();
if(!(method === 'GET' || method === 'POST' || method === 'HEAD')){
throw new Error('method must either be GET, POST, or HEAD');
}
//Setup our request
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
//Once the request has completed fire the callback with relevant arguments
//you should handle in your callback if it was successful or not
callback(xhr.responseText, xhr.status, xhr);
}
};
//Open and send request
xhr.open(method, url, async);
xhr.send();
}
Now we have a replacement for $.get() and $.getScript() that work just as simply:
pullScript(file1, function(data, status, xhr){
console.log(data);
console.log(status);
console.log(xhr);
});
pullScript(file2);
pull(file3, function loadReturn(data, status){
if(status == 200){
document.querySelector('#content').innerHTML = data;
}
}
Mozilla Developer Network provides an example that works asynchronously and does not use 'onreadystatechange' (from #ShaneX's answer) that is not really present in a HTMLScriptTag:
function loadError(oError) {
throw new URIError("The script " + oError.target.src + " didn't load correctly.");
}
function prefixScript(url, onloadFunction) {
var newScript = document.createElement("script");
newScript.onerror = loadError;
if (onloadFunction) { newScript.onload = onloadFunction; }
document.currentScript.parentNode.insertBefore(newScript, document.currentScript);
newScript.src = url;
}
Sample usage:
prefixScript("myScript1.js");
prefixScript("myScript2.js", function () { alert("The script \"myScript2.js\" has been correctly loaded."); });
But #Agamemnus' comment should be considered: The script might not be fully loaded when onloadFunction is called. A timer could be used setTimeout(func, 0) to let the event loop finalize the added script to the document. The event loop finally calls the function behind the timer and the script should be ready to use at this point.
However, maybe one should consider returning a Promise instead of providing two functions for exception & success handling, that would be the ES6 way. This would also render the need for a timer unnecessary, because Promises are handled by the event loop - becuase by the time the Promise is handled, the script was already finalized by the event loop.
Implementing Mozilla's method including Promises, the final code looks like this:
function loadScript(url)
{
return new Promise(function(resolve, reject)
{
let newScript = document.createElement("script");
newScript.onerror = reject;
newScript.onload = resolve;
document.currentScript.parentNode.insertBefore(newScript, document.currentScript);
newScript.src = url;
});
}
loadScript("test.js").then(() => { FunctionFromExportedScript(); }).catch(() => { console.log("rejected!"); });
window.addEventListener('DOMContentLoaded',
function() {
var head = document.getElementsByTagName('HEAD')[0];
var script = document.createElement('script');
script.src = "/Content/index.js";
head.appendChild(script);
});
Here's a version that preserves the accept and x-requested-with headers, like jquery getScript:
function pullScript(url, callback){
pull(url, function loadReturn(data, status, xhr){
if(status === 200){
var script = document.createElement('script');
script.innerHTML = data; // Instead of setting .src set .innerHTML
document.querySelector('head').appendChild(script);
}
if (typeof callback != 'undefined'){
// If callback was given skip an execution frame and run callback passing relevant arguments
setTimeout(function runCallback(){callback(data, status, xhr)}, 0);
}
});
}
function pull(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
callback(xhr.responseText, xhr.status, xhr);
}
};
xhr.open('GET', url, true);
xhr.setRequestHeader('accept', '*/*;q=0.5, text/javascript, application/javascript, application/ecmascript, application/x-ecmascript');
xhr.setRequestHeader('x-requested-with', 'XMLHttpRequest');
xhr.send();
}
pullScript(URL);

Categories

Resources