4

I am using chartjs (with the dart interface https://pub.dartlang.org/packages/chartjs) and trying to make it deferred by injecting a <script src="chartjs.js"></script> into the head section and awaiting it's load event to then use the lib.
I am getting this exception: Cannot read property 'Chart' of undefined.

It does not happen when the script is within the head of the html before dart.

So, is it possible to load a JS lib after Dart loaded?

4
  • 1
    I have an experience to load js-library during angular component is being initialized. github.com/alexd1971/angular_grecaptcha/blob/master/lib/src/… In ngOnInit script tag is created and added to DOM. In ngAfterViewInit awaiting the script is loaded and initializing component. But this unfortunately does not always work. For example here: github.com/alexd1971/angular_flatpickr. I have not found out why yet. Mar 12, 2019 at 6:04
  • Sounds like a problem with waiting for loading to complete. I used this approach a while ago and it worked for me (not Chartjs though) Mar 12, 2019 at 9:12
  • I tried loading the script on main.dart to make sure it is loaded, but still didn't work
    – Jonathan
    Mar 12, 2019 at 12:43
  • The problem is that certain JS files can not be added to the dom after dart is loaded. Just tested it by simple adding the <script src=chartjs></script> after main.dart.js script and it threw this error: Error: Mismatched anonymous define() module: function(){var define,module,exports;
    – Jonathan
    Mar 12, 2019 at 13:16

3 Answers 3

3

this is a problem in DDC. It addeds require.js to the HTML and conflicts with other libs.
https://github.com/dart-lang/sdk/issues/33979

The solution I've found is to manually remove the header section that uses requirejs from the third-party lib you want to use.

For example, take chartjs: https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.js

You remove this two lines:

typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(function() { try { return require('moment'); } catch(e) { } }()) :
typeof define === 'function' && define.amd ? define(['require'], function(require) { return factory(function() { try { return require('moment'); } catch(e) { } }()); }) :

Then the file can be lazily added to the DOM without conflicts.

This is my code to lazily fetch scripts:

class ClientUtils {
    static final _scriptFetched = <String, Future<bool>>{};

    static ScriptElement _scr(String url) => new ScriptElement()
      ..async = true
      ..type = 'text/javascript'
      ..src = url;

    static Future<bool> fetchScript(String url,
            {String contextCheck}) async {
        bool shouldCheck = contextCheck?.isNotEmpty == true;

        hasContext() => js.context.hasProperty(contextCheck) &&
                    js.context[contextCheck] != null;

        if (shouldCheck && hasContext())
            return true;

        if (!_scriptFetched.containsKey(url)) {
            Completer<bool> c = new Completer<bool>();

            if (!shouldCheck) {
                ScriptElement s = _scr(url)
                    ..onLoad.forEach((Event e) {
                        c.complete(true);
                    });

                document.body.children.add(s);
            } else {
                Timer.periodic(Duration(milliseconds: 300), (t) {
                    if (hasContext()) {
                        t.cancel();
                    }
                    c.complete(true);
                });

                document.body.children.add(_scr(url));
            }

            _scriptFetched[url] = c.future;
        }
        return _scriptFetched[url];
    }
}

3

found a better way!

lets remove the define variable after dart loads, then any third-party lib works when added async :D

add this to your main():

import 'dart:js';

void main() {
  context.callMethod('fixRequireJs');
}

and in your index.html:

    <script type="text/javascript">
      window.fixRequireJs = function()
      {
        console.log('define is ', typeof define);
        if (typeof define == 'function') {
          console.log('removing define...');
          delete define;
          window.define = null;
        }
      }
    </script>
0

You can try the deferred as syntax:

import 'package:chartjs/chartjs.dart' deferred as chartjs;

void main() {
    chartjs.loadLibrary().then(() { ... });
}
1
  • but that make the interface deferred, not the actual js script, right?
    – Jonathan
    Mar 12, 2019 at 12:42

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.