![](/img/trans.png)
[英]Appropriate use of the 'route' and 'path' libs on a Dart server
[英]is it possible to lazily use JS libs with Dart?
我正在使用 chartjs(帶有 dart 接口https://pub.dartlang.org/packages/chartjs )並試圖通過將<script src="chartjs.js"></script>
注入 head 部分來推遲它並等待它的加載事件然后使用該庫。
我收到此異常:無法讀取未定義的屬性“圖表”。
當腳本位於 dart 之前的 html 頭部時,不會發生這種情況。
那么,是否可以在加載 Dart 后加載 JS 庫?
這是 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 加載后刪除define
變量,然后添加異步時任何第三方庫都可以工作:D
將此添加到您的 main():
import 'dart:js';
void main() {
context.callMethod('fixRequireJs');
}
在你的 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>
您可以嘗試deferred as
語法:
import 'package:chartjs/chartjs.dart' deferred as chartjs;
void main() {
chartjs.loadLibrary().then(() { ... });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.