【问题标题】:How to import javascript library from url and store it in a variable?如何从 url 导入 javascript 库并将其存储在变量中?
【发布时间】:2021-07-16 12:32:18
【问题描述】:

背景

我通常用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 一起使用。

我还找到了following post,因此尝试了:

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

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

我还尝试了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() 再次无法识别。

如果这个问题已经在别处得到解答,请参考我,我找不到。

【问题讨论】:

  • 你最后的sn-p代码确实有效。 say_hi 未在您的脚本中定义。但是,klotezooi 已定义。然后你可以这样做,window.test = klotezooi;
  • 对不起,你是对的,我拿了一个旧的 hello.js 文件。正确的现在在帖子中。最后的代码 sn -p 仍然不起作用(hello.say_hi() 不是函数)。我也刚刚尝试了 say_hi() 但这也没有用,无论如何这不是我想要的。
  • 在你上次的 sn-p 中,不要使用 hello.say_hi();,而是使用 var hello = {'say_hi':window.say_hi};,然后你可以使用 hello.say_hi();
  • 还是一样:Uncaught TypeError: hello.say_hi is not a function。我在 shopify 和我的本地计算机上尝试过。仅供参考,只是在做:window.say_hi();也不行。
  • 确保脚本加载正确。这是一个工作示例:jsfiddle.net/ptLjezrv

标签: javascript html import


【解决方案1】:

确保正确加载脚本。如果您在页面中附加带有 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();
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 2019-09-30
    • 2014-03-05
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多