0

i am using following code to create a external js and integrate it on each route(page)

if(document.getElementById('mainJs') !=null){
      document.getElementById('mainJs').remove();
    }
    const main = document.createElement('script');
    main.src = '../assets/js/main.js';
    main.type = 'text/javascript';
    main.async = false;
    main.id = "mainJs";
    main.charset = 'utf-8';
    document.getElementsByTagName('head')[0].appendChild(main);

but whenever the route switches my external js stops working

i am not sure if this is exactly the reason but in the chrome's Event-Listeners name of the js changes from Before Route Change to After Route Change

is the name change of the js causing this problem? if yes what should i do solve this?

  • 1
    Is there a reason to why you are trying to append a JS script in the HTML page instead of just using it in your TS files? – YounesM Feb 14 '20 at 09:53
  • Perhaps you could tell us what exactly are you trying to achieve by this approach, that would help. – Jiri Kralovec Feb 14 '20 at 09:59
  • Does this answer your question? [Add .js scripts in Angular 2 project](https://stackoverflow.com/questions/41652742/add-js-scripts-in-angular-2-project) – YounesM Feb 14 '20 at 10:02
  • @YounesM if i load the JS files through angular.json script array (as mentioned in the link), the js will only work one time after page load, as soon as the route changes, JS will stop working (since angular is SPA). – Mirza Tarique Feb 14 '20 at 17:01
  • @JiriKralovec basically i have few external JS files that i need to use in my angular project, and since i need it throughout the project, that's why i am binding it to the every time my route changes. if you have any other approach ; please let me know – Mirza Tarique Feb 14 '20 at 17:10
  • This may be more flexible solution to your problem - [Angular 2: external js file variables are accessible from component](https://stackoverflow.com/questions/47366887/angular-2-external-js-file-variables-are-accessible-from-component). If you need to perform some action, say, on every page load, make a master class to inherit and perform the task globally. You can always override parent class function by children therefore making case-specific callbacks. – Jiri Kralovec Feb 15 '20 at 21:35

0 Answers0