0

1.我本地的js文件sdk.js是

    (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.被异步调用的远程js是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 就像
<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>

我无法访问 us-sdk.js 中定义的函数和对象。我正在使用在 Apache 服务器下运行的本机 java 脚本代码。让我知道我做错了什么?

4

1 回答 1

0

将事件监听器添加到包含的脚本的加载事件中:

(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);

于 2020-05-13T15:45:53.237 回答