How to load external scripts dynamically in Angular?

前端 未结 15 951
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 06:48

I have this module which componentize the external library together with additional logic without adding the

15条回答
  •  醉梦人生
    2020-11-22 07:07

    Yet another option would be to utilize scriptjs package for that matter which

    allows you to load script resources on-demand from any URL

    Example

    Install the package:

    npm i scriptjs
    

    and type definitions for scriptjs:

    npm install --save @types/scriptjs
    

    Then import $script.get() method:

    import { get } from 'scriptjs';
    

    and finally load script resource, in our case Google Maps library:

    export class AppComponent implements OnInit {
      ngOnInit() {
        get("https://maps.googleapis.com/maps/api/js?key=", () => {
            //Google Maps library has been loaded...
        });
      }
    }
    

    Demo

提交回复
热议问题