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?
Dynamic loadingThose files can be loaded asynchronously in JavaScript. To load a JavaScript file dynamically: Create a script element. Set the src , async , and type attributes.
To include a JavaScript library in your TypeScript application you must first include it in your HTML file as a script tag. To use the library you must add the following to one of your ts files: declare var libraryVar: any; Replace libraryVar with a variable, function, or class within your JavaScript library.
Try to load external JavaScript on component load as below :
loadAPI: Promise<any>; constructor() { this.loadAPI = new Promise((resolve) => { this.loadScript(); resolve(true); }); } public loadScript() { var isFound = false; var scripts = document.getElementsByTagName("script") for (var i = 0; i < scripts.length; ++i) { if (scripts[i].getAttribute('src') != null && scripts[i].getAttribute('src').includes("loader")) { isFound = true; } } if (!isFound) { var dynamicScripts = ["https://widgets.skyscanner.net/widget-server/js/loader.js"]; for (var i = 0; i < dynamicScripts.length; i++) { let node = document.createElement('script'); node.src = dynamicScripts [i]; node.type = 'text/javascript'; node.async = false; node.charset = 'utf-8'; document.getElementsByTagName('head')[0].appendChild(node); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With