我正在尝试使用import函数动态导入TensorFlow.js。但是,我总是收到一个TypeError: t is undefined错误。下面的代码是一个简单的HTML文件,它重新创建了错误。
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
import("https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js")
.then(tf => { console.log(tf); });
</script>
</body>
</html>请注意,我还希望动态创建将使用TensorFlow.js库的代码。任何关于如何在浏览器中动态导入TensorFlow.js并运行动态创建的使用其函数的代码的帮助都是非常感谢的。下面是与我的最终目标类似的代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
let code = `import("https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js").then(tf => {
// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// Generate some synthetic data for training.
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
// Train the model using the data.
model.fit(xs, ys, {epochs: 10}).then(() => {
model.predict(tf.tensor2d([5], [1, 1])).print();
// Open the browser devtools to see the output
});
});
`;
let script = document.createElement("script");
script.type = "text/javascript";
script.appendChild(document.createTextNode(code));
document.body.appendChild(script);
</script>
</body>
</html>发布于 2019-10-06 16:23:11
您可以很好地动态添加脚本元素吗?
const el = document.createElement('script')
el.src = "https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js";
el.onload = (() => {
const script = document.createElement('script');
script.innerHTML = "console.log(tf)";
document.body.appendChild(script);
})();
document.body.appendChild(el);替代
您也可以更早地追加脚本,但在加载tf之前不要执行
示例如下
const script = document.createElement('script');
script.innerHTML = `
function someDependentCode() {
console.log(tf);
// put all dependent code string here
}
`;
document.body.appendChild(script); //code is added but not called
const el = document.createElement('script')
el.src = "https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js";
el.onload = someDependentCode(); //dependent code can now execute
document.body.appendChild(el);https://stackoverflow.com/questions/58255449
复制相似问题