简体   繁体   中英

How to run third party JS script in Angular 6

I have some third party JS scripts in angular app which has $(document).ready functions, At start everything works fine but when I change the routes via routerLink then some functionality does not work but when page is reloaded then it works.

I have tried importing JS files in angular.json and index.html.

Please help if you have any solution for this problem.

Thanks.

This happens because the page is fully loaded once and then only portions of the page are re-loaded when you navigate on your routes (SPA). So, the $(document).ready event is fired only once, when the page is loaded.

An workaround to achieve this is fire your third party script on your own in some angular life-cycle, for example, angular router NavigationEnd event:

this.router.events.subscribe(event => {
  if (event instanceof NavigationEnd) {
     // do your stuff here
  }
});

But this is bad, it's easy to lost control. This could be better if you encapsulate the third party library in some Angular component, eg a directive, to avoid $(document).ready pattern.

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