javascriptasynchronous-javascriptself-executing-function

How to use functions of java script library which is called asynchronously by my web page?


1. My local js file sdk.js is

    (function(sdkUrl,b,flag)
    {
        if (window[b])
            return;
        if (!window.JSON)
            return;
        let url = sdkUrl;
        let h = /Chrome\/(\d+)/.exec(navigator.userAgent);
        h && Number(h[1]) >= 55 && "assign" in Object && "findIndex" in [] && (url += "");
        let js = document.createElement("script");
        js.src = url;
        js.async = !0;
        flag && (js.crossOrigin = "anonymous");
        let i = document.getElementsByTagName("script")[0];
        i.parentNode && i.parentNode.insertBefore(js, i)
    })('http:\/\/phoenix.loc\/sdk\/v1\/gen.js','UB',true);

2. remote js which is being called asynchronously is ub-sdk.js

(function(global)
{
    'use strict';
    var UB = {
        firstName: "John",
        lastName : "Doe",
        id       : 5566,
        fullName : function()
        {
            return this.firstName + " " + this.lastName;
        }
    };
    if (typeof module != 'undefined' && module.exports)
    {
        module.exports = UB;
    }
    else if ( typeof define === "function" && define.amd )
    {
        define( "UB", [], function()
        {
            return UB;
        });
    }
    else
    {
        global.UB = UB;
    }
}(windows));
  1. index.html is like
<html>
<head>
    <title>JS SDK Demo</title>
</head>
<body>
<script src="sdk.js"></script>
<script type="text/javascript">
    console.log(UB.fullName());
</script>
</body>
</html>

I am not able to access functions and objects defined in us-sdk.js. I am using native java script code running under Apache server. Let me know where I am doing it wrong?


Solution

  • Add an eventlistener to the included script's load-event:

    (function(sdkUrl, b, flag) {
      if (window[b])
        return;
      if (!window.JSON)
        return;
      let url = sdkUrl;
      let h = /Chrome\/(\d+)/.exec(navigator.userAgent);
      h && Number(h[1]) >= 55 && "assign" in Object && "findIndex" in [] && (url += "");
      let js = document.createElement("script");
      js.src = url;
      js.async = !0;
    
      //
      // Listen here:
      //
      js.addEventListener('load', function() {
        console.log($)
      });
    
      flag && (js.crossOrigin = "anonymous");
      let i = document.getElementsByTagName("script")[0];
      i.parentNode && i.parentNode.insertBefore(js, i)
    })('https://code.jquery.com/jquery-3.5.1.slim.min.js', 'UB', true);