0

I followed this answer https://stackoverflow.com/a/7719185/842837 to load javascript asynchronously. How do I some pass data to this 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 to I send config to external js file?

EDIT I was going though google analytics code. They also load their script asynchronously, and use config data from 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 to do the same thing, in a more readable way.

Community
  • 1
  • 1
jerrymouse
  • 16,964
  • 16
  • 76
  • 97

1 Answers1

1

No, you can't pass parameters like that and have the script read them in.

Technically you could grab them from the tag, but that would be a real mess.

Could you just output a script block before you include the 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 is attached to window name space => window['config'];

Therefore , as alternative , you could remain the same code that you have , however, you need just to replace var config= by window.config=; By that , config will be visible for 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>
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254