Tuesday, August 21, 2012

Detect if Facebook is blocked by firewall (revised)

I previously wrote about detecting when a user's firewall is preventing them from seeing Facebook like buttons and plugins.  I updated the detection algorithm so that it was more reliable, and wouldn't block other scripts from loading.  I also moved the script that loaded the Facebook library to load dynamically, so it wouldn't attempt to load unless Facebook was available. This prevented the ghostly spinning loading icon if it wasn't ever going to load.
var fbs = new Array ('http://connect.facebook.net/en_US/all.js#appId=193562130691498&xfbml=1');

function addScript(sourcefile) {
    var newscript =    document.createElement('script');
    newscript.setAttribute("type","text/javascript");
    newscript.setAttribute("src",sourcefile);
    document.getElementsByTagName("head")[0].appendChild(newscript);
}

function DetectFB() {
    var fbdetect = new Image();
    fbdetect.onerror = function () {
        //FB is blocked
         document.getElementById('fb-container').style.display='none';
        //document.getElementById('fb-container').innerHTML ='Sorry, FB is blocked.';
    }
    fbdetect.onload = function () {
        //FB is not blocked
        for (ssrc in fbs) {
            addScript(fbs[ssrc]);
        }
        setTimeout('FB.XFBML.parse()', 2000);

    }
   
    fbdetect.src = (document.location.protocol=='https:' ? "http://static" : "https:s-static") +".ak.fbcdn.net/rsrc.php/v1/yp/r/kk8dc2UJYJ4.png?"+Math.random();
}

function addLoadEvent(func) {
  if (window.addEventListener)
    window.addEventListener("load", func, false);
  else if (window.attachEvent)
    window.attachEvent("onload", func);
  else { // fallback
    var old = window.onload;
    window.onload = function() {
      if (old) old();
      func();
    };
  }
}

addLoadEvent(DetectFB);

1 comment: