asynchronous - How to pass data to external javascript script, loaded asynchronously -
i followed answer https://stackoverflow.com/a/7719185/842837 load javascript asynchronously. how pass data external file?
current code:
<script id="js-widget-o2ba1y" type='text/javascript'> (function() { function async_load(){ var config = { 'module': 'hyperdesign', 'user-name': 'john doe', 'user-email': 'john@doe.com' }; var id = "js-widget-o2ba1y"; var embedder = document.getelementbyid(id); var s = document.createelement('script'); s.type = 'text/javascript'; s.async = true; var u = 'http://external.javascript.file.js'; s.src = u + ( u.indexof("?") >= 0 ? "&" : "?") + 'ref=' + encodeuricomponent(window.location.href); embedder.parentnode.insertbefore(s, embedder); } if (window.attachevent) window.attachevent('onload', async_load); else window.addeventlistener('load', async_load, false); })(); </script>
how send config
external js file?
edit going though google analytics code. load script asynchronously, , use config data 3rd party website:
<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','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'ua-xxxxx-y', 'auto'); ga('send', 'pageview'); </script>
i need same thing, in more readable way.
no, can't pass parameters , have script read them in.
technically grab them tag, real mess.
could output script block before include file?
<script type="text/javascript"> var config = { 'module': 'hyperdesign', 'user-name': 'john doe', 'user-email': 'john@doe.com' }; </script> <script id="js-widget-o2ba1y" type='text/javascript'> //you code </script>
by that, config
object attached window
name space => window['config']
;
therefore , alternative , remain same code have , however, need replace var config=
window.config=
; , config
visible external js .
<script id="js-widget-o2ba1y" type='text/javascript'> (function() { function async_load(){ window.config = { 'module': 'hyperdesign', 'user-name': 'john doe', 'user-email': 'john@doe.com' }; var id = "js-widget-o2ba1y"; //-----rest of code </script>
Comments
Post a Comment