0

I am working in angular2 vs typescript.

In my app.component.ts file i have to load the script files on demand based current navigator language. So i have added my function like below(home.component.ts),

export class HomeComponent {
constructor() {
    this.loadDynmicallyScript();
  } 
public loadDynmicallyScript() {
    let node = document.createElement('script');
    node.src = "../node_modules/xxxxxxxxxx/xx." +   navigator.language"+".min.js";
    node.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(node);
 }

But this not works. But i have to load the files on demand based on current navigator language. How to achive this? Thanks for any help.

Sasi Dhivya
  • 501
  • 2
  • 7
  • 25
  • Any error message in the browser console – Günter Zöchbauer Feb 25 '18 at 13:23
  • http://localhost:3000/node_modules/xxxxxxxxx/xx.ar-AE.min.js Failed to load resource: the server responded with a status of 404 (Not Found) – Sasi Dhivya Feb 25 '18 at 13:27
  • so just the path is wrong or your server doesn't serve such a file – Günter Zöchbauer Feb 25 '18 at 13:29
  • but whaterver i edit i face this issue only. have to took file from node modules how to resolve this. – Sasi Dhivya Feb 25 '18 at 13:32
  • 1
    This question has already been answered over [here](https://stackoverflow.com/questions/44204417/dynamically-load-external-javascript-file-from-angular-component) – Gokul Shanth Feb 25 '18 at 14:04
  • yes @GokulShanth i too checked this now. But here the problem was the files get loaded ,called the function after the components get rendered completely. but the files is no use here – Sasi Dhivya Feb 25 '18 at 14:18
  • 3
    @GokulShanth It hasn't. And the question was marked as dupe by mistake. The OP wasn't specific enough, but obviously, the problem is that loaded script isn't external, and we don't have node_modules publicly available. – Estus Flask Feb 25 '18 at 21:27

2 Answers2

0

import * as _script from 'assets/js/index.js';

you can import like this but before importing the scripts change your function to exports then use.

and call the needed functions that needs to be loaded on the pageload in ngOnInit

karthik
  • 1
  • 2
0

In order for the script to be loaded, it should be available for loading. Unless you're willing to copy script files manually to public folder, adding a script manually with document.createElement is wrong move.

Webpack already handles dynamic imports. This requires some additional measures to make sure that lazy loaded script will be bundled by Webpack. Import name should be suitable for static analysis, additional options can be provided through comments.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565