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;

function* loadScriptAGen() {
  while (true) {

function* loadScriptBGen() {
  while(true) {

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

And in the Angular components:

import {loadScriptA, loadScriptB} from "blabla";


ngOnInit() {

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)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.