如何100%保证我的动态加载脚本在调用特定函数之前加载完毕?

问题描述 投票:0回答:1

我有一个正在组件中动态加载的脚本。该脚本有一个函数将在另一个函数(如

window["scriptFunction"]
)中使用。我的问题是,有时在加载脚本之前调用此函数,然后我们会收到错误。

import { Component, OnInit, OnDestroy, Renderer2, Inject } from '@angular/core';

export class HomeComponent implements OnInit, OnDestroy {
   this.script: any;

   public constructor(
      private _renderer2: Renderer2,
      @Inject(DOCUMENT) private _document: Document
   ) {
       this.someVariable = false;
   }

   public async ngOnInit(): Promise<void> {
      this.insertDynamicallyScript();
   }

   public ngOnDestroy(): void {
      // after user leave this page I remove the script
      this._renderer2.removeChild(this._document.body, this.script);
   }

   public insertDynamicallyScript(): void {
      this.script = this._renderer2.createElement('script');
      this.script.type = 'text/javascript';
      this.script.src = 'url.here';
      this.script.async = false;
      this._renderer2.appendChild(this._document.body, this.script);
      this.script.onload = () => console.log('Script loaded');
   }

   public userButtonActionFunction(): Promise<void> {
      try {
          if (window['scriptFunction']) {
             await window['scriptFunction'].doSomething();
          } else {
             // script did not load yet and we get here
             // How to make sure that my script is always loaded when I reach this user function?
          }
      } catch (exception) {
         // do something
      } finally {
           // do something
      }
   }
}

我已经尝试过解决这个问题,但它对我不起作用。这个问题偶尔会发生一次,比如不到 1% 的请求进入这个阶段。用户交互并单击按钮,函数

userButtonActionFunction()
被调用,但脚本尚未加载,导致页面上出现一些奇怪的行为。

javascript angular async-await
1个回答
0
投票

angular.json
文件中,会有scripts数组,将URL包含在该数组中,即可使用该函数。

"scripts": [
  "url.here"
]
© www.soinside.com 2019 - 2024. All rights reserved.