addJavaScriptSource function

Future<bool> addJavaScriptSource(
  1. String scriptSource, {
  2. bool addToBody = false,
  3. bool async = false,
})

Adds a JavaScript path (scriptSource] into DOM.

addToBody If true adds into body node instead of head node. async If true, the script will be executed asynchronously as soon as it is available, and not when the page has finished parsing.

Implementation

Future<bool> addJavaScriptSource(String scriptSource,
    {bool addToBody = false, bool async = false}) async {
  var scriptInDom = getScriptElementBySRC(scriptSource);

  var prevCall = _addedJavaScriptsSources[scriptSource];

  if (prevCall != null) {
    if (scriptInDom != null) {
      return prevCall;
    } else {
      var removed = _addedJavaScriptsSources.remove(scriptSource);
      assert(removed != null);
    }
  }

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

  print('ADDING <SCRIPT>: $scriptSource > into body: $addToBody');

  Element parent;
  if (addToBody) {
    parent = querySelector('body')!;
  } else {
    parent = querySelector('head')!;
  }

  var script = ScriptElement()
    ..type = 'text/javascript'
    // ignore: unsafe_html
    ..src = scriptSource;

  if (async) {
    script.async = true;
  }

  var completer = Completer<bool>();

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

  parent.children.add(script);

  var call = completer.future;
  _addedJavaScriptsSources[scriptSource] = call;

  return call;
}