如何将代码从index.html移动到组件



我把下面的代码放在index.html中,它就可以工作了。

<!-- Smartsupp Live Chat script -->
<script type="text/javascript">
var _smartsupp = _smartsupp || {};
_smartsupp.key = '';
window.smartsupp ||
(function (d) {
var s,
c,
o = (smartsupp = function () {
o._.push(arguments);
});
o._ = [];
s = d.getElementsByTagName('script')[0];
c = d.createElement('script');
c.type = 'text/javascript';
c.charset = 'utf-8';
c.async = true;
c.src = 'https://www.smartsuppchat.com/loader.js?';
s.parentNode.insertBefore(c, s);
})(document);
</script>

如何从组件内部移动要执行的代码?

我试着把代码放在一个函数中,例如ngAfterViewInit((,但我得到了像Property 'smartsupp' does not exist on type 'Window & typeof globalThis'.这样的错误

export class AppComponent  {

ngAfterViewinit(){
var _smartsupp = _smartsupp || {};
_smartsupp.key = '';
window.smartsupp ||
(function (d) {
var s,
c,
o = (smartsupp = function () {
o._.push(arguments);
});
o._ = [];
s = d.getElementsByTagName('script')[0];
c = d.createElement('script');
c.type = 'text/javascript';
c.charset = 'utf-8';
c.async = true;
c.src = 'https://www.smartsuppchat.com/loader.js?';
s.parentNode.insertBefore(c, s);
})(document);

}
}

您可以将代码移动到js文件startup.js

然后将脚本包含在ngInit 中的TS文件中

var script = document.createElement('script');
script.src = "assets/startup.js";
document.head.appendChild(script);

在您的脚本中,您在窗口中添加了smartsupp对象

这样你就可以对它设置一个条件,以确保它已加载

if(window && window.smartsupp)
{
// do something 
}

最新更新