I develop a library that needs to load async in pages. My script load:
<script type="text/javascript">
(function(w,d) {
var po = d.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'my_function-sdk.js';
var s = d.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})(window, document);
</script>
I want to use the function immediately below:
<script>
my_function("test");
</script>
Or in a click:
<a href="#" onclick="my_function('other test');">test click</a>
The function definition in file my_function-sdk.js
:
function my_function(param) {
console.log("in correct function");
console.log(param);
}
I want that console.log print "in correct function" how was defined in my function on file my_function-sdk.js
.
JSFiddle: https://jsfiddle.net/adrianogodoy/n7ahygoj/8/
EDIT:
I want to do like Google Analytics, using ga
function immediately bellow the load script or any other place without receive a not defined error:
<script>
(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', 'UA-XXXXXXX-1', 'auto');
ga('send', 'pageview');
</script>