I’m trying to add a script element, which has var myVar = "hello world", and immediately after, I want to use myVar. Unfortunately, typeof myVar is undefined, unless I do a setTimeout of more than 0. setTimeout of 0 does not work. I copied Google Analytic’s way of creating the script element, and they seem to have it working just fine. Am I missing something?
Note: for some reason, jsbin is not behaving the same as if you were to copy/paste this code into a .html file and try it locally. I suppose jsbin already has a delay, which makes the setTimeout of 0 work.
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.defer = false;
ga.src = 'http://bakersdozen13.lfchosting.com/test.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})(); // note: the () executes it immediately (or it should!)
$("#out").append('typeof myVar is ' + typeof myVar); // "undefined" :(
setTimeout(function() {
$("#out").append('<br/>typeof myVar is ' + typeof myVar); // "undefined" :(
}, 0);
setTimeout(function() {
$("#out").append('<br/>typeof myVar is ' + typeof myVar); // "string"
}, 1000);
The script file has to load. There is no way to wait for it to load. Since it looks like you are using jQuery, utilize getScript()
JSFiddle