Is there a way to make my script behave like the Google Analytics JavaScript snippet? Here is an example of what I have:
(function(d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.src = 'myjs.js';
s.parentNode.insertBefore(g, s);
}(document, 'script'));
In this script, a class is defined. But when I try to call it like this:
var newClass = new myclass('myparam');
I receive a 'not defined' error. However, if I wait and call it again in the console, the error no longer occurs. It seems like the script has not fully loaded yet, which is why the class does not exist.
On the other hand, you can call Google Analytics functions directly after importing, as shown here:
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '[userid]', '[website]');
How can I achieve similar behavior with my own script?