How to load the script file immediately (dynamically added) before continue?

前端 未结 1 1191
孤城傲影
孤城傲影 2021-01-23 18:37

I have loaded script file like below code in angular home.component.ts file

export class HomeComponent {
    constructor() {
        this.loadDynmicallyScript()         


        
相关标签:
1条回答
  • 2021-01-23 19:29

    You can return a promise to chain calls

    export class HomeComponent {
        constructor() {
            this.loadDynmicallyScript()
            .then(() => {
              this.doSomethingWhenScriptIsLoaded();
            });
        } 
         public loadDynmicallyScript():Promise {
            var script = document.createElement('script');
            script.src = "../node_modules/xxxxxx/i18n/xx.min.js";
            script.async =false;
            document.head.appendChild(script);
            return Promise((resolve, reject) => {
              script.onload = resolve;
            });    
         }
    

    or just pass a function to the onLoad to be called when the script was loaded

    export class HomeComponent {
        constructor() {
            this.loadDynmicallyScript()
        } 
         public loadDynmicallyScript():Promise {
            var script = document.createElement('script');
            script.src = "../node_modules/xxxxxx/i18n/xx.min.js";
            script.async =false;
            document.head.appendChild(script);
            script.onload = () => this.doSomethingWhenScriptIsLoaded();
         }
    
    0 讨论(0)
提交回复
热议问题