Dynamically load external javascript file from Ang

2019-01-04 12:23发布

I am creating an Angular application using Angular 4 and the CLI. I am trying to add the SkyScanner search widget into one of my components.

Skyscanner Widget Example

Part of the implementation requires the addition of a new external script:

<script src="https://widgets.skyscanner.net/widget-server/js/loader.js" async></script>

I am not sure of the correct way to reference this file. If I add the script into my index.html file, the widget doesn't load unless a full page refresh is performed. I assume the script tries to manipulate the DOM on load and the elements don't exist when the script runs.

What is the correct way to load the script only when the component containing the Skyscanner widget is loaded?

7条回答
何必那么认真
2楼-- · 2019-01-04 13:09

You can do one thing

if you have angular-cli.json

then you can declare to script

like

"scripts": ["../src/assets/js/loader.js"]

And then declare skyscanner in your component

like

declare var skyscanner:any;

Thats it!

Hope this help you

查看更多
登录 后发表回答