(function modulePreloadPolyfill() {
  const MODULE_PRELOAD_SELECTOR = 'link[rel="modulepreload"]';
  const PROCESSED_FLAG = "ep";

  const relList = document.createElement("link").relList;
  const browserSupportsModulePreload =
    relList &&
    typeof relList.supports === "function" &&
    relList.supports("modulepreload");

  if (browserSupportsModulePreload) {
    return;
  }

  for (const modulePreloadLink of document.querySelectorAll(MODULE_PRELOAD_SELECTOR)) {
    preloadModuleLink(modulePreloadLink);
  }

  const observer = new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.type !== "childList") {
        continue;
      }

      for (const addedNode of mutation.addedNodes) {
        if (addedNode.tagName === "LINK" && addedNode.rel === "modulepreload") {
          preloadModuleLink(addedNode);
        }
      }
    }
  });

  observer.observe(document, {
    childList: true,
    subtree: true
  });

  function preloadModuleLink(linkElement) {
    if (linkElement[PROCESSED_FLAG]) {
      return;
    }

    linkElement[PROCESSED_FLAG] = true;

    const fetchOptions = buildFetchOptions(linkElement);
    fetch(linkElement.href, fetchOptions);
  }

  function buildFetchOptions(linkElement) {
    const fetchOptions = {};

    if (linkElement.integrity) {
      fetchOptions.integrity = linkElement.integrity;
    }

    if (linkElement.referrerPolicy) {
      fetchOptions.referrerPolicy = linkElement.referrerPolicy;
    }

    if (linkElement.crossOrigin === "use-credentials") {
      fetchOptions.credentials = "include";
    } else if (linkElement.crossOrigin === "anonymous") {
      fetchOptions.credentials = "omit";
    } else {
      fetchOptions.credentials = "same-origin";
    }

    return fetchOptions;
  }
})();
