Search code examples
javascriptcssangulartypescriptangular5

How to load External JS and CSS files into Angular 5 (files loading with delay)


As title suggested I am facing some issues while trying to import the external js and css files into Angular 5 Application.

Here is code snippet that I did tried till now

Component.ts :

  ngOnInit() {
    this.loadScript();        // tried with constructor as well
  }

  loadScript () {
    const head = document.getElementsByTagName('head')[0];
    const link = document.createElement('link');
    const s = this.document.createElement('script');

    s.type = 'text/javascript';
    s.src = 'https://**/assets/js/patterns/name.min.js';

    link.id = 'pattern';
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.href = 'https://**/assets/js/patterns/name.min.css';
    link.media = 'all';

    head.appendChild(link);
    const __this = this;
    s.onload = function () { __this.afterScriptAdded(); };
    this.elementRef.nativeElement.appendChild(s);
 }

Also tried to load from scss file by adding this line

 @import url("https://**/assets/js/patterns/name.min.css");

I am able to see the files in network tab but problem is this files loading gets a delay so my functions rendered without this knowledge and later it loaded with no use.

It works only on reloading where if we navigate from one component to another. It would freeze the first time and after reloading the page would be seen properly along with the dynamic scripts.

Came across few questions related to it but nothing worked

  1. Dynamically load external javascript file from Angular component
  2. How to load external scripts dynamically in Angular?

is anyone came across similar situation.. any help highly appreciated :)


Solution

  • Initially tried to avoid setTimeout for this to work.

    However, seems like nothing is working except loading the files after some delay, where we are allowing the component to be rendered completely and then attaching our js (+ css) file to the native element.

    ...
    
    ngOnInit() {
       setTimeout(() => {
            this.loadScript();
       }, 100);
    }
    
    ...
    

    Though it's working, still setting static timeout value. Please let me know if you have better solution for this.

    Happy Coding. :)