Skip to main content

Adding facebook buttons without invalidating XHTML document

To add a facebook button without making my XHTML document invalid on my blog, I had to do the following:

  1. Add xmlns:fb="https://www.facebook.com/2008/fbml" to html start tag.
  2. Modify the wordpress template to insert fb elements.
  3. Dynamically generate rb-root element and facebook script (note: my use of location.protocol to avoid including insecure contents when user accesses my site via https):
if (window.addEventListener) {
    window.addEventListener('load', function () {
        var fbRoot = document.createElement('div');
        fbRoot.id = 'fb-root';
        document.body.appendChild(fbRoot);
        var element = document.createElement('script');
        element.src = location.protocol + '//connect.facebook.net/en_US/all.js#xfbml=1';
        document.body.appendChild(element);
    });
}

I've seen some random sites suggesting to use document.write to output elements in fb namespace but I'd object to such an approach. Sure, that'll shut the validator up and makes your document pass but your document will still be invalid as soon as script runs on your browser and inserts an element in undefined namespace, and that's bad.

Apparently, twitter's share button doesn't support https so I can't add it on my website.

June 26th -- facebook apparently loads some png file via http connection. Shame on them! I'm disabling the facebook button for now until I figure out how to fix that.