Aurelia 视图中的脚本标签未执行

Script tag in Aurelia view is not executed

我正在向简单的 aurelia 视图添加一个简单的脚本块:

<template>
    <script type="text/javascript">
    alert('Hello!');
    </script>
</template>

脚本永远不会 运行,即使视图呈现正确并且我可以看到脚本块确实出现在 DOM 中。

我也尝试过通过 viewModel 动态插入脚本块,还尝试过:

 <script type="text/javascript" src="http://blah"></script>

我知道这样做不是最佳做法,但我正在尝试集成第三方小部件,然后它会呈现 iframe。上面显示的警报只是验证我所看到的问题的一种简单方法。

现实生活场景如下:

我需要将其附加到 DOM 并让它执行。我正在通过 fetch 调用上面的 url 然后我执行响应来解决这个问题,但这似乎是一种 tedious/hacky 的方式。

我建议采用此答案中提供的解决方案:Use JS variable to set the src attribute for <script> tag

在您的 VM 的 bindattached 方法中(最有可能):

let scriptURL = api.getURL();

let scriptElement = document.createElement('script');

scriptElement.src = scriptURL;
scriptElement.onload = () => {
    // do anything you need to do here, or call a VM method
    this.someVMMethod();
};

this.scriptElementInHead = document.querySelector('head').appendChild(scriptElement);

如果需要,在 unbinddetached 方法中卸载组件时,您甚至可以通过保留对它的引用并将其从 head 元素中删除来删除脚本元素。

 detached() {
   document.querySelector('head').removeChild(this.scriptElementInHead);
 }