如何在mithril.js中使用另一个js



我需要在我的网站中包含一个第三方js库,纯HTML文件中的一个工作示例类似于

<div id="app"></div>
<script src="app.js"></script>
<script>App.initialize();</script>

基本上,initialize((函数将首先用加载动画填充#app,然后从外部API获取数据,最后用它生成的html代码加载#app

一切都很好,直到我用mithril.js重写它,类似

const page = {
view: () => [
m('script', {src: 'app.js'}),
m(app)
]
} 
const app = {
oncreate: () => { App.initialize();},  
view: () => m('#app')
}

当我渲染page时,我仍然可以看到加载的动画,但在它消失后,#app中什么都没有显示。预期的代码没有像普通HTML文件那样加载到#app中,控制台中也没有错误消息。

我在mithril.js中错过了什么或做错了什么吗?

我认为以这种方式加载脚本可能存在某种时间问题。同样,如果它把东西放进身体元素,那么mithril可能会在上面重新渲染。也许可以尝试这样的东西:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
</head>
<body>
<script src="https://unpkg.com/mithril/mithril.js"></script>
<div id="page"></div>
<script type="text/javascript">
let appLoaded = false;
let mithrilLoaded = false;
let appTimer = null;
let mithrilTimer = null;
function stopSync() {
console.log('Sync done, init app.')
appLoaded = mithrilLoaded = true;
window.clearInterval(appTimer);
window.clearInterval(mithrilTimer);
appTimer = mithrilTimer = null;
App.initialize();
}
function startAppSync() {
console.log('App loaded, start sync with mithril.')
appLoaded = true;
appTimer = window.setInterval(checkAppSync, 100);
}
function startMithrilSync() {
console.log('Mithril loaded, start sync with app.')
mithrilLoaded = true;
mithrilTimer = window.setInterval(checkMithrilSync, 100);
}
function checkAppSync() {
console.log('Checking mithril from app sync.')
if (mithrilLoaded) {
stopSync();
}
}
function checkMithrilSync() {
console.log('Checking app from mithril sync.')
if (appLoaded) {
stopSync();
}
}
const page = {
view: function() {
return m('', [
m('script', {
onload: function () {
startAppSync();
},
src:'app.js'
}),
m(app),
]);
}
}
const app = {
oncreate: function() {
startMithrilSync();
},
view: function() {
return m('#app');
}
}
m.mount(document.getElementById('page'), page);
</script>
</body>
</html>

这里的更多信息是,默认情况下,注入的脚本是异步加载的。您可以使用document.createElement('script').async在浏览器中对此进行测试。

https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement#dynamically_importing_scripts

最新更新