Created
February 2, 2012 18:51
-
-
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
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
// 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