繁体   English   中英

如何从 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.say_hi();

如果是这样,你怎么做?

研究

我知道您可以按如下方式使用“导出”和“导入”功能

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

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

我还尝试了这篇文章(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();
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM