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 ;)
jQuery's $jQ.getScript()
is an asynchronous call. So if you were calling tweetStream()
immediately after the getScript()
, it would run before the script arrived.
You can call tweetStream()
from (or as) a callback instead.
$jQ.getScript('/path-to/tweet.js', function() {
tweetStream();
});
or this if you don't care about the value of this
in tweetStream()
.
$jQ.getScript('/path-to/tweet.js', tweetStream);