addCssSource function

Future<bool> addCssSource(
  1. String cssSource, {
  2. int? insertIndex,
})

Add a CSS path using a link element into head DOM node.

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

Implementation

Future<bool> addCssSource(String cssSource, {int? insertIndex}) async {
  var linkInDom = getLinkElementByHREF(cssSource, 'stylesheet');

  var prevCall = _addedCssSources[cssSource];

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

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

  print('ADDING <LINK>: $cssSource');

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

  var script = LinkElement()
    ..rel = 'stylesheet'
    ..href = cssSource;

  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;
  _addedCssSources[cssSource] = call;

  return call;
}