我需要包括一个第三方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中遗漏了什么或做错了什么?
发布于 2021-07-22 04:23:27
我认为以这种方式加载脚本可能存在某种时间问题。此外,如果它将对象放入body元素中,那么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
https://stackoverflow.com/questions/68472897
复制相似问题