Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load JS script on component level (not at startup) [duplicate]

Tags:

angular

I have lots of JS files in my project. I want to load them when particular module or component load not when the app start.

How to do this?

Currently, I am loading them in index.html. The other way is to add them in angular-cli.json. But both ways will load the JS files at the startup. However, I need them to to load when the particular page or module runs.

like image 628
Sudhanshu sharma Avatar asked Aug 24 '17 12:08

Sudhanshu sharma


People also ask

How do I check if a JavaScript script is loaded?

To detect if the script has already loaded, I use the following method (in general): Create a common library function to dynamically load all scripts. Before loading, it uses the isScriptLoaded(src) function above to check whether the script has already been added (say, by another module).


2 Answers

Just write a normal script loader :

   public loadScript() {
            let body = <HTMLDivElement> document.body;
            let script = document.createElement('script');
            script.innerHTML = '';
            script.src = 'url';
            script.async = true;
            script.defer = true;
            body.appendChild(script);
    }

and then call it where ever you want :

export class MyComponent{

    ngOnInit(){
        this.loadScript();

    }

}

But if those files are Typescript files, you can lazy load them as well in a numerous ways:

1- Using the default module level lazy loading

2- Using webpack's require

3- Using SystemJs module loader

like image 108
Milad Avatar answered Oct 17 '22 23:10

Milad


I have already given answer of this question but some how not able to mark as duplicate.

Please check this link : https://stackoverflow.com/a/44276683/6606630

where you can find how to load the external javascript at runtime at component level.

You have to create script element on the fly and then append it in DOM.

In that loadScript function i have just check existence of single js, if you have multiple js then you have to make some changes in logic.

Still if you have any query let me know, i will help you

like image 24
Sandip - Frontend Developer Avatar answered Oct 18 '22 00:10

Sandip - Frontend Developer