ReferenceError: "twttr is not defined" even while using twttr.ready()
It appears that twttr
is not initialized yet. Make sure the script (//platform.twitter.com/widgets.js
) is loading before the block of code you have.
This is the reason you're getting undefined (twttr).
After seeing your edits, it's quite clear what is happening. Your scripts are appending the head and loading the scripts after the page is loading. Right after you're executing code that depends on the stuff you've injected into the head and are still loading which is why twttr
is not initialized yet.
Try this code block below:
window.addEventListener("load", function() {
window.fbAsyncInit = function() {
FB.Event.subscribe('edge.create', function(targetUrl) {
ga('send', 'social', 'facebook', 'like', targetUrl);
});
FB.Event.subscribe('edge.remove', function(targetUrl) {
ga('send', 'social', 'facebook', 'unlike', targetUrl);
});
}
document.getElementById('tweetjs').addEventListener('load', function() {
twttr.ready(function (twttr) {
twttr.events.bind('tweet', function(e){
if(!e) return;
ga('send', 'social', 'twitter', 'tweet', theURL);
})
});
}, false);
}, false);
If you want cross browser support, you may want to follow what they did in their function to check for window.addEventListener first, and then fall back to window.attachEvent for older browsers.
For those experiencing issues of 'twttr is undefined', the following solved it for me...
Include this script after the body opening and make sure you remove the widget.js scripts from your button embeds if copied & pasted over.
window.twttr = (function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
t = window.twttr || {};
if (d.getElementById(id)) return t;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
t._e = [];
t.ready = function(f) {
t._e.push(f);
};
return t;
}(document, "script", "twitter-wjs"));