Aurelia视图中的脚本标签未执行 [英] Script tag in Aurelia view is not executed

查看:65
本文介绍了Aurelia视图中的脚本标签未执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm adding a simple script block to a simple aurelia view:

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

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

The script is never run, even though the view is rendered correctly and I can see that the script block does appear in the DOM.

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

I have also tried dynamically inserting a script block via the viewModel and also tried with:

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

我知道这样做并非最佳做法,但我正在尝试集成第三方小部件,然后再渲染iframe.上面显示的警报只是一种验证我所看到的问题的简单方法.

I understand it's not best practice to do this, but I'm trying to integrate a third party widget that will then render an iframe. The alert shown above is just a simple way of the verifying the issue that I'm seeing.

现实生活场景如下:

  • 我从视图模型向第三方进行api调用.
  • 返回以下内容:

  • I make an api call to a third party from my view model.
  • The following is returned:

<script type='text/javascript' language='JavaScript' src =' https://secure.na1.echosign.com/public/embeddedWidget ? `wid = CBFCIBAA3AAABLblqZhBU33GaMRZ2lMelHKzti7RkanxMP5v- uW_f8CEiKoopNNofJWyXhmE56Su3HTbY *& token = CBNCKBAAHBCAABAARNiZ7Yba0h7ryLaQRBAdTdH9UrJZ>

<script type='text/javascript' language='JavaScript' src='https://secure.na1.echosign.com/public/embeddedWidget? ` wid=CBFCIBAA3AAABLblqZhBU33GaMRZ2lMelHKzti7RkanxMP5v- uW_f8CEiKoopNNofJWyXhmE56Su3HTbY*&token=CBNCKBAAHBCAABAARNiZ7Yba0h7dnLaQRBAdTdH9UrJZKryP' />

我需要将此附加到DOM并执行.我正在通过fetch调用上述url来解决此问题,然后执行响应,但这似乎是一种乏味/骇人的方式.

I need to append this to the DOM and have it execute. I am working around this issue by calling the above url via fetch and then I exec the response, but it seems like a tedious/hacky way of doing it.

推荐答案

我建议采用此答案中提供的解决方案:

I would recommend adapting the solution provided in this answer: Use JS variable to set the src attribute for <script> tag.

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

In your VM's bind or attached method (most likely):

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元素中删除.

If need be, you can even remove the script element by keeping a reference to it and removing it from the head element when the component is being unloaded in the unbind or detached methods.

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

这篇关于Aurelia视图中的脚本标签未执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆