我使用带有影子dom的自定义web组件将html文件加载到元素中,我似乎找不到一种方法将其作为html文件加载而不延迟头脚本和样式链接。
换句话说,脚本没有加载,head标记中的外部css文件被延迟到html完全加载之后。
html文件如下所示:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html lang="en">
<head>
<title>My Document</title>
<link href="/MyStyles.css" rel="stylesheet" type="text/css" />
<script src="/MyScripts.js" type="text/javascript"></script>
</head>
<body>
<!-- Other Main Tags -->
<script src="/AnotherScript.js" type="text/javascript"></script>
</body>
</html>
JavaScript:
customElements.define('ui-include', class extends HTMLElement {
async connectedCallback() {
let ref = this.getAttribute('ref')
const shadow = this.attachShadow({ mode: 'open' })
shadow.innerHTML = 'Loading...';
fetch(`/documentviewer.aspx/GetContent`,
{
body: JSON.stringify({ reference: ref }),
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
})
.then(r => r.json())
.then(r => {
// r.d is the response html string (html file example above)
shadow.innerHTML = r.d ;
})
.catch(e => {
console.error(e)
})
.then(() => {
console.log('done')
})
}
})
HTML:
<ui-include ref="Document_123"></ui-include>
页面加载后,在检查ui-include
时。 标题标记不再显示。 就像它被打开一样,下面是一张截图:
如何将html响应字符串视为实际文档并将其加载到web组件中?
您可以使用DOM解析器,如下所示:
customElements.define('ui-include', class extends HTMLElement {
async connectedCallback() {
let ref = this.getAttribute('ref')
const shadow = this.attachShadow({ mode: 'open' })
shadow.innerHTML = 'Loading...';
fetch(`/documentviewer.aspx/GetContent`, {
body: JSON.stringify({ reference: ref }),
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
})
.then(r => r.json())
.then(r => {
shadow.children[0].remove();
const dp = new DOMParser();
const f = document.createDocumentFragment();
f.appendChild(dp.parseFromString(r.d, 'text/html'))
shadow.appendChild(f);
})
.catch(e => console.error(e))
.then(() => console.log('done'));
}
})