Skip to content

Instantly share code, notes, and snippets.

@amix
Created February 2, 2012 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amix/1725092 to your computer and use it in GitHub Desktop.
Save amix/1725092 to your computer and use it in GitHub Desktop.
Implementation of script communication that can be used to do long polling (comet) and JSONP communication. Uses Cross-Origin Resource Sharing
// For more information about this check: http://amix.dk/blog/post/19677
ScriptCommunicator = {
sourceJavaScript: function(uri, on_success, on_error) {
var xhr = ScriptCommunicator.createCORSRequest('GET', uri);
if(xhr) {
xhr.onload = function() {
eval(xhr.responseText);
on_success();
};
xhr.onerror = function() {
if(on_error)
on_error();
}
xhr.send();
}
else {
var script_channel = document.createElement('script');
script_channel.async = false;
script_channel.src = uri;
script_channel.type = "text/javascript";
script_channel.className = 'temp_script';
var agent = navigator.userAgent.toLowerCase();
if(agent.indexOf("msie") != -1) { //IE
script_channel.onreadystatechange = function() {;
if(!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
return on_success();
}
}
}
else {
script_channel.onload = function() {
on_success();
}
}
var body = document.getElementsByTagName('body')[0];
body.appendChild(script_channel);
}
},
createCORSRequest: function (method, url){
var xhr = new XMLHttpRequest();
if("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment