dart - 是否可以在 Dart 中懒惰地使用 JS 库?

标签 dart dart-2

我正在使用 chartjs(带有 dart 接口(interface) https://pub.dartlang.org/packages/chartjs )并试图通过注入(inject) <script src="chartjs.js"></script> 来推迟它进入 head 部分并等待它的加载事件然后使用 lib。
我收到此异常:无法读取未定义的属性“图表”。

当脚本位于 dart 之前的 html 头部时,不会发生这种情况。

那么,是否可以在加载 Dart 后加载 JS lib?

最佳答案

这是 DDC 中的一个问题。
它将 require.js 添加到 HTML 并与其他库发生冲突。
https://github.com/dart-lang/sdk/issues/33979

我找到的解决方案是从您要使用的第三方库中手动删除使用 requirejs 的标题部分。

以chartjs为例:https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.js

您删除这两行:

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) { } }()); }) :

然后可以将文件延迟添加到 DOM 中而不会发生冲突。

这是我懒惰地获取脚本的代码:
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];
    }
}

关于dart - 是否可以在 Dart 中懒惰地使用 JS 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55113108/

相关文章:

charts - 如何在 flutter、x 轴和 y 轴上向图表添加名称?

function - Flutter,如何减少重复的widget

dart - 在三元运算中检查 null

flutter - 如何在 flutter 中显示 html 布局链接?

dart - Flutter中如何返回Map

amazon-web-services - 在 Flutter 中从 AWS S3 上传和获取媒体文件

ubuntu - 安装dart-sdk后找不到pub命令

android - flutter 插件 : "Methods marked with @UiThread must be executed on the main thread."

dart - 尽管使用Dart 2.0,仍无法省略 'new'关键字

dart - Dart 1 书籍是否仍然与学习 Dart 2 相关