Defer loading of Facebook Like Button Script

这一生的挚爱 提交于 2019-12-04 06:48:53
ghost

Use the setTimeout luke!

setTimeout( function () {
   (function(d,s,id){
         // load js
         ...
      }
      (document, "script", "facebook-jssdk")
   );
}, 3000);

You can throw the load in another 'thread' to async or Defer it

setTimeout works but it's not real defer, since if the page finished loading after the time set (in this case 3 seconds) the like button will be loaded before the page finished loading.

I put the like button's javscript code inside my own function and nested it inside the

<script>
    function FbButtonLoad(){
      (function(d,s,id){
         // load js
         ...
      }
      (document, "script", "facebook-jssdk")
   );
}
</script>

then I set it in the body tag to run on page load:

<body onload="FbButtonLoad();">

The button appears on the page where I left it's containers:

<div id="fb-root"></div>
<div class="fb-like" data-send="true" data-width="350" data-show-faces="true"></div>
Dave Spelts

Another slightly less than perfect solution (HTML5 only) would be to load the library on DOMContentLoaded.

document.addEventListener('DOMContentLoaded', function() {
    (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")
);  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!