Reputation: 10489
In Internet Explorer <9, at least, linking to a blocked resource (due to firewalls, WebSense, etc.) will return an error. For instance, if Facebook is blocked, linking to the Facebook SDK JavaScript file will result in an error in Internet Explorer.
Is it possible to test if a website is blocked in JavaScript, before linking to the external JavaScript file, for the following purposes:
Upvotes: 5
Views: 5664
Reputation: 54780
Looking at the facebook SDK, looks like it gets injected asynchronously by inserting a script element into the head. This means all you have to do is create the callback handler and if facebook is blocked then that will never be called. You shouldn't get any browser script error. So you should be able to do something like:
<div id="fb-root"></div>
<script>
var FACEBOOK_BLOCKED = true;
window.fbAsyncInit = function() {
FACEBOOK_BLOCKED = false;
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelURL : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
For a more general use case, a similar approach will work with any script that you can call using a JSON-P approach. This, of course, requires that the server takes a callback function as a parameter (or automatically calls a pre-named function):
// Load some SDK Asynchronously
(function(d){
var js = d.createElement('script');
js.src = "http://www.example.com?callback=myfunc";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
var SCRIPT_LOADED = false;
var myfunc = function() {
SCRIPT_LOADED = true;
}
UPDATE
Just came across this method, you might want to give it a shot:
function loadScript(sScriptSrc, oCallback) {
var oHead = document.getElementById('head')[0];
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.src = sScriptSrc;
// most browsers
oScript.onload = oCallback;
// IE 6 & 7
oScript.onreadystatechange = function() {
if (this.readyState == 'complete') {
oCallback();
}
}
oHead.appendChild(oScript);
}
Upvotes: 3
Reputation: 1725
you can use jquery's getScript function, it has a success function that is only executed if the script has been loaded , check it out here : http://api.jquery.com/jQuery.getScript/
Upvotes: 0