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.

7
  • Any error message in the browser console Commented Feb 25, 2018 at 13:23
  • localhost:3000/node_modules/xxxxxxxxx/xx.ar-AE.min.js Failed to load resource: the server responded with a status of 404 (Not Found) Commented Feb 25, 2018 at 13:27
  • so just the path is wrong or your server doesn't serve such a file Commented Feb 25, 2018 at 13:29
  • 1
    This question has already been answered over here Commented Feb 25, 2018 at 14:04
  • 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. Commented Feb 25, 2018 at 21:27

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.