如何从 url 导入 javascript 库并将其存储在变量中?

How to import javascript library from url and store it in a variable?

背景

我通常在 python 中编码,并且习惯于按如下方式导入库:

import numpy as np

然后访问图书馆:

a = np.array([1,2,3])

但是在 javascript 中我无法让事情以这种方式工作。我可以通过 url 导入库,如下所示:

<script src="//cdn.shopify.com/s/files/1/0561/6726/8513/t/1/assets/hello.js?v=6940067293431132177" crossorigin="anonymous"></script>
say_hi(); //say_hi is defined in hello.js

这行得通,但非常混乱。我现在有一堆可以直接访问的函数,但这会污染我的命名空间。最重要的是,函数来自哪个库还不是很清楚。

问题

有没有一种方法可以通过使用 URL 来访问我的 'hello' 库,如下所示:

hello.say_hi();

如果是,你是怎么做到的?

研究

我知道您可以使用 'export' 和 'import' 函数,如下所示

import * as hello from './hello.js';

在 hello.js 中导出定义为:

export {say_hi};

但是我需要从 URL 中导入它,我不知道它如何与 URL 一起使用。

我也找到了 并尝试了:

<script src="//cdn.shopify.com/s/files/1/0561/6726/8513/t/1/assets/hello.js?v=17694146303704268990"></script>
const hello = window.hello;
hello.say_hi()

但在这种情况下,hello 是未定义的...

我也尝试了 this post(Rahul Srivastava 的回答):

var hello = document.createElement('script');
hello.setAttribute('src','//cdn.shopify.com/s/files/1/0561/6726/8513/t/1/assets/hello.js?v=17694146303704268990');
document.head.appendChild(hello);
hello.say_hi();

但又一次 hello.say_hi() 无法识别。

如果这个问题已经在其他地方得到解答,请参考我,我找不到。

确保脚本加载正确。如果您在页面中附加带有 JavaScript 的脚本,则必须等到它加载后才能尝试调用其中的函数。

https://jsfiddle.net/t3gkyxf4/

var script = document.createElement('script');
script.setAttribute('src','//cdn.shopify.com/s/files/1/0561/6726/8513/t/1/assets/hello.js?v=17694146303704268990');
document.head.appendChild(script);
// waits until the page is fully loaded before calling or copying functions
window.onload = function() {
  var test = {
    'say_hi': window.say_hi
  };
  test.say_hi();
};