They take so long to load, I want to do it after Dom loaded.
<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";
f开发者_运维百科js.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));
</script>
<div class="fb-like" data-href="http://www.mywebsite.com<%=HttpContext.Current.Request.Url.AbsolutePath %>"
data-send="false" data-width="450" data-show-faces="true">
</div>
First, if you're not already using jQuery, you don't need jQuery. Follow a solution more like the one here, or if you don't need that kind of complexity and support for very old browsers, you can put together a much simpler version.
Once you have your "DOM ready handler", you should do one of the following two things:
Move the JS SDK loading code into your DOM ready handler. No matter how many social plugins you have on the page, you only need to load the SDK once.
Take
xfbml: true
out ofFB.init(...)
, if you have it (in this case, you don't), and takexfbml=1
out of the SDK URL. This prevents social widgets from being parsed and initialized immediately. Then, callFB.XFBML.parse()
in your DOM ready handler. See the documentation here for that method.
Thanks amosrivera :) Heres a code snippet I whiped up for anyone who finds this:
var Interface = {
Facebook: (function () {
function Init() {
}
function LikeButton() {
var $facebookLike = $('.facebook-like');
$facebookLike.html('<div id="fb-root"></div>');
(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'));
$facebookLike.append('<div class="fb-like" data-href="'+$facebookLike.data('url')+'" data-send="false" data-width="450" data-show-faces="true"></div>');
}
function Comments() {
var $facebookComments = $('.facebook-comments');
$facebookComments.html('<div id="fb-root"></div>');
(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'));
$facebookComments.append('<div class="fb-comments" data-href="'+$facebookComments.data('url')+'" data-num-posts="10" data-width="500"></div>');
}
return {
Init: Init,
LikeButton: LikeButton,
Comments: Comments
}
})()
}
Just use the document ready event from jQuery
$(document).ready(function(){
//code here
});
Demo: http://jsfiddle.net/ZCcyy/
Note that this will only wait until the dom is ready. If you want to load until the whole page is loaded including images use the window load event instead.
$(window).load(function(){
// code here
});
精彩评论