document.createElement('script')与jQuery .getScript之间的区别

时间:2010-12-19 19:28:26

标签: javascript jquery getscript script-tag

我遇到了.getScript在某些奇怪案件中工作的问题。

例如,这只适用于在需要时加载脚本。

function twitterSDK() {
    $jQ.getScript('http://platform.twitter.com/widgets.js');
}

function diggShare() {
    $jQ.getScript('http://widgets.digg.com/buttons.js');
}

function buzzShare() {
    $jQ.getScript('http://www.google.com/buzz/api/button.js');
}

然而,它似乎不适用于我写的几个脚本。如果我调用.getScript来获取这个JS文件,我已经上传到Pastebin(http://pastebin.com/GVFcMJ4P)并且调用tweetStream();没有任何反应。但是,如果我执行以下操作,则可以:

var twitter = document.createElement('script');
twitter.type = 'text/javascript';
twitter.async = true;
twitter.src = '/path-to/tweet.js';
$jQ('.twitter-section').append(twitter);
tweetStream();

我做错了什么?任何帮助都会很棒,谢谢!

P.S。哪种方法更快或更有效?

注意:我的代码不在pastebin上托管,我只是将我服务器上的.js文件的内容上传到该站点,因此很容易共享。我没有使用pastebin进行托管;)

1 个答案:

答案 0 :(得分:4)

jQuery的$jQ.getScript()是异步调用。因此,如果您在tweetStream()之后立即调用getScript(),它将在脚本到达之前运行。

您可以从(或作为)回调中调用tweetStream()

$jQ.getScript('/path-to/tweet.js', function() {
    tweetStream();
});
如果您不关心thistweetStream()的价值,请

$jQ.getScript('/path-to/tweet.js', tweetStream);
相关问题