简体   繁体   中英

JS file load on Angular component onInit

I'm having an error while loading a flipbook library, it says Cannot set properties of null (setting 'innerHTML') and the line that is making this error:
const loadingMessageElement = document.getElementById('loading-message');
loadingMessageElement.innerHTML = 'Preparing document...';
So I think this is because the file is loading before the DOM is ready, so how can I load the file when the DOM is ready?
To clarify a little, this library is not at node_modules, is in my assets folder and I call it in my angular.json in the scripts section, I already try to import and declare the library in my ts file but I always got the error Cannot find module 'flipbook' or its corresponding type declarations.

I make it work with this function in my TS file:

ngOnInit(): void { 
    this.loadScripts();
  }

  // Method to dynamically load JavaScript
  loadScripts() {
  
    // This array contains all the files/CDNs
    const dynamicScripts = [
       'assets/flipbook/flipbook.js'
    ];
    for (let i = 0; i < dynamicScripts.length; i++) {
      const node = document.createElement('script');
      node.src = dynamicScripts[i];
      node.type = 'text/javascript';
      node.async = false;
      document.getElementsByTagName('body')[0].appendChild(node);
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM