Jobsdev
Jobsdev

Reputation: 1039

How to import library javascript in component (within the component)?

I am using angular 2 with angular cli

I know how to import using angular-cli.json. However I want to import within component.

The reason is that the file is too large and I do not want it to be loaded at the initial system load.

How can I load an external library when a specific component loads?

My system will use a library to receive payment of my client. I need to import this library into my payment component: https://stc.pagseguro.uol.com.br/pagseguro/api/v2/checkout/pagseguro.directpayment.js

After import I need to use some functions of this imported file to generate a token. With this token I can carry out the payment transactions.

My problem is that I do not want to upload this file to the initial upload. I would like to load only when a particular route is called. exemple: /pay-signature

Upvotes: 0

Views: 294

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71961

Since TypeScript 2.4 you've got the option to use an import statement within the code itself, you can write your own loader to load a library:

async getLib(name: string): Promise<any> {
    return await import(name);
}

You should wrap this around a Resolve service for any path where you use said library.

If you do not want to/can use the latest TypeScript, you can create a script tag and listen for the load event:

getLib(name: string): Promise<any> {
    return new Promise((resolve) => {
       let script: HTMLScriptElement = document.createElement('script');
       script.addEventListener('load', r => resolve());
       script.src = string;
       document.head.appendChild(script);      
    });    
}

Upvotes: 1

Related Questions