prefetchHref function

Future<bool> prefetchHref(
  1. String href, {
  2. int? insertIndex,
  3. bool? preLoad,
})

Prefetch a HREF using a link element into head DOM node.

href The path to the CSS source file. insertIndex optional index of insertion inside head node.

Implementation

Future<bool> prefetchHref(String href,
    {int? insertIndex, bool? preLoad}) async {
  var rel = 'prefetch';

  if (preLoad ?? false) {
    rel = 'preload';
  }

  var linkInDom = getLinkElementByHREF(href, rel);

  var prevCall = _prefetchedHref[href];

  if (prevCall != null) {
    if (linkInDom != null) {
      return prevCall;
    } else {
      var removed = _prefetchedHref.remove(href);
      assert(removed != null);
    }
  }

  if (linkInDom != null) {
    return true;
  }

  var head = querySelector('head') as HeadElement?;

  var script = LinkElement()
    ..rel = rel
    ..href = href;

  var completer = Completer<bool>();

  script.onLoad.listen((e) {
    completer.complete(true);
  }, onError: (e) {
    completer.complete(false);
  });

  if (insertIndex != null) {
    insertIndex = Math.min(insertIndex, head!.children.length);
    head.children.insert(insertIndex, script);
  } else {
    head!.children.add(script);
  }

  var call = completer.future;
  _prefetchedHref[href] = call;

  return call;
}