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

时间:2011-02-02 23:30:20

标签: javascript jquery

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

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

问题在于它阻止了该部分的页面加载,如何在页面加载后插入此标记并仍然执行脚本?我想以一种不引人注目的方式做这些想法吗?

5 个答案:

答案 0 :(得分:9)

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

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

答案 1 :(得分:3)

您可以使用jquery.getScripts异步加载它。

答案 2 :(得分: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)

作为Inject the script tag事件的回调,

document ready进入dom。

答案 4 :(得分:0)

你可以做点什么:

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