If you're .NET users like us, you may know that there are facilities to help you request the current page URL.
The problem with requesting the URL from the server is that it returns the URL that the server uses (the ugly one, the one that hasn't been re-written), and when it comes to links and search engine optimisation, it pays to keep links to your site consistent. The answer is to supply your Facebook Like button with a URL generated by JavaScript. More about this at the bottom of the article, but for now, let's get started with adding a basic Like button to your website.
Get Started
Start by visiting
Facebook's Like button generator. Play around with the wizard to generate the style of
Like button you desire. Get the code that's generated when you're happy.
So, you should have a piece of code like:
<div class="fb-like" data-href="www.yourdomain.com" data-send="false" data-layout="button_count" data-width="60" data-show-faces="true"></div>
Put this code where you want your Like button. This code may look useless at the moment, and indeed on its own it is. You need to include the JavaScript SDK for Facebook on your page.
Include the JavaScript SDK
Dump the following code to reference Facebook's Javascript SDK, above the snippet provided by facebook (an example of which is provided above).
The JavaScript SDK can be incorporated onto the page by including the following code.
<div id="fb-root"></div>
<script> (function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));
</script>
Asynchronous loading allows all of your content to load before or at the same time as the Like button. This can be important, because generally the Like button will take some time to load.
Provide The Current Page URL
We need to add a new attribute to the XFBML element provided by facebook. Give the snippet an "id" attribute. This will enable us to call a JavaScript that can identify and change values in the snippet. In this example, we've given this element the ID, 'fb':
<div class="fb-like" id="fb" data-href="www.yourdomain.com" data-send="false" data-layout="button_count" data-width="60" data-show-faces="true"></div>
Somewhere on your page, but below this snippet, place the following JavaScript:
<script type="text/javascript">
var sUrl = window.location;
document.getElementById('fb').setAttribute('href', sUrl);
</script>
In most cases you should be able to use the above code to generate a dynamic module/control that provides you with a flexible Like button that can be applied to any page.