document.createElement('script') 与 jQuery .getScript 之间的区别
在某些奇怪的情况下,我一直无法让 .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
来获取我已上传到 Pastebin 的 JS 文件 ( 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();
我做错了什么?任何帮助都会很棒,谢谢!
PS 哪种方法更快或更有效?
注意:我的代码未托管在 Pastebin 上,我只是将服务器上的 .js 文件的内容上传到该网站,以便轻松共享。我不会利用pastebin来托管;)
I've been having an issue getting .getScript
to work in some odd cases.
For instance, this works to load the scripts only when needed.
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');
}
However it doesn't seem to work on a few scripts that I wrote. If I call .getScript
to fetch this JS file I've uploaded to Pastebin ( http://pastebin.com/GVFcMJ4P ) and call tweetStream();
nothing happens. However, if I do the following it works:
var twitter = document.createElement('script');
twitter.type = 'text/javascript';
twitter.async = true;
twitter.src = '/path-to/tweet.js';
$jQ('.twitter-section').append(twitter);
tweetStream();
What am I doing wrong? Any help would be awesome, thanks!
P.S. Which method is faster or more efficient?
Note: My code isn't hosted on pastebin, I just uploaded the contents of the .js file that is on my server to that site so it is easy to share. I am not leeching of pastebin for hosting ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
jQuery 的
$jQ.getScript()
是异步调用。因此,如果您在getScript()
之后立即调用tweetStream()
,它将在脚本到达之前运行。您可以从(或作为)回调调用
tweetStream()
。或者如果您不关心
tweetStream()
中this
的值,则可以使用 this。jQuery's
$jQ.getScript()
is an asynchronous call. So if you were callingtweetStream()
immediately after thegetScript()
, it would run before the script arrived.You can call
tweetStream()
from (or as) a callback instead.or this if you don't care about the value of
this
intweetStream()
.