我正在使用 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/