# Using function* (generator) to load external scripts in Angular application

I'm working on an Angular application that requires two external scripts to be loaded for certain components (about 12 separate ones). Script loading is only relevant if the user navigates to a certain part of the site that includes these components, but for most users it's not.

Each component exists as a separate page, and two of them will never be rendered at the same time.

In order to load the scripts required, I've landed on the following solution:

Having an external-scripts util file with the following:

function loadScript(url: string) {
const body = <HTMLDivElement>document.body;
const script = document.createElement("script");
script.innerHTML = "";
script.src = url;
body.appendChild(script);
}

function* loadScriptAGen() {
loadScript("http://somescript.js");
while (true) {
yield;
}
}

function* loadScriptBGen() {
loadScript(http://someotherscript.js");
while(true) {
yield;
}
}

export const loadScriptA = loadScriptAGen();
export const loadScriptB = loadScriptBGen();


And in the Angular components:

import {loadScriptA, loadScriptB} from "blabla";

...

ngOnInit() {
loadScriptA.next();
loadScriptB.next();
}


I'd appreciate any feedback on any possible drawbacks on using generators for this purpose. Comments about making a "generator creator function" etc. are not necessary; if the number of scripts to be loaded increases I will implement this, but for the time being I don't mind having those two as it increases readability over having a function that returns a generator function.

The purpose is of course to ensure:

• the scripts are only loaded when a component that needs them is rendered
• the scripts are only embedded into the <body>-tag once

(the loadScript-method itself is not my code)

• 1) it would make more sense to yield/resolve in script element's onload event, 2) no need to set innerHTML – wOxxOm Nov 8 '19 at 15:56