使用jQuery在页面加载后加载外部脚本

3

我有点困惑如何做到这一点,基本上我有一个页面,通过JavaScript插入Facebook分享按钮:

<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>

问题是它会阻塞页面在那个部分的加载,我该如何在页面加载后插入此标记并仍然执行脚本?我想以不显眼的方式完成它,有什么建议吗?
5个回答

9

$(document).ready 中使用 jQuery 的 getScript 命令。这将在页面加载后下载脚本。例如:

$(document).ready(function() {
    $.getScript("http://static.ak.fbcdn.net/connect.php/js/FB.Share", function() {
        alert("Script loaded and executed.");
    });
});

3

尝试类似以下的代码:

$(document).ready(function() {
    var script = document.createElement( 'script' );
    script.src = "http://static.ak.fbcdn.net/connect.php/js/FB.Share";
    script.onload=optionallyDoSomethingWithTheScriptYouJustLoaded();//not needed
    var headID = document.getElementsByTagName("head")[0];         
    headID.appendChild(script);
 });

3

0

你可以这样做:

$(function() {
  $.getScript('http://static.ak.fbcdn.net/connect.php/js/FB.Share', function() {
    //do nothing here
  });
});

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接