w3.js ist ziemlich cool.
https://www.w3schools.com/lib/w3.js
und wir sind konzentriert
w3-einschließen-html
aber betrachten Sie den folgenden Fall
- popup.html
- popup.js
- include.js
- partials
- head
- bootstrap-css.html
- fontawesome-css.html
- all-css.html
- hello-world.html
<!-- popup.html -->
<head>
<script defer type="module" src="popup.js"></script>
<meta data-include-html="partials/head/all-css.html">
</head>
<body>
<div data-include-html="partials/hello-world.html"></div>
</body>
<!-- bootstrap-css.html -->
<link href="https://.../bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<!-- fontawesome-css.html -->
<link rel="stylesheet" href="https://.../font-awesome/5.15.4/css/all.min.css" />
<!-- all-css.html -->
<meta data-include-html="bootstrap-css.html">
<meta data-include-html="fontawesome-css.html">
<!--
If you want to use w3.js.include, you should change as below
<meta w3-include-html="partials/head/bootstrap-css.html">
<meta w3-include-html="partials/head/fontawesome-css.html">
Of course, you can add the above in the ``popup.html`` directly.
If you don't want to, then consider using my scripts.
-->
<!-- hello-world.html -->
<h2>Hello World</h2>
Drehbuch
// include.js
const INCLUDE_TAG_NAME = `data-include-html`
/**
* @param {Element} node
* @param {Function} cb callback
* */
export async function includeHTML(node, {
cb = undefined
}) {
const nodeArray = node === undefined ?
document.querySelectorAll(`[${INCLUDE_TAG_NAME}]`) :
node.querySelectorAll(`[${INCLUDE_TAG_NAME}]`)
if (nodeArray === null) {
return
}
for (const node of nodeArray) {
const filePath = node.getAttribute(`${INCLUDE_TAG_NAME}`)
if (filePath === undefined) {
return
}
await new Promise(resolve => {
fetch(filePath
).then(async response => {
const text = await response.text()
if (!response.ok) {
throw Error(`${response.statusText} (${response.status}) | ${text} `)
}
node.innerHTML = text
const rootPath = filePath.split("/").slice(0, -1)
node.querySelectorAll(`[${INCLUDE_TAG_NAME}]`).forEach(elem=>{
const relativePath = elem.getAttribute(`${INCLUDE_TAG_NAME}`) // not support ".."
if(relativePath.startsWith('/')) { // begin with site root.
return
}
elem.setAttribute(`${INCLUDE_TAG_NAME}`, [...rootPath, relativePath].join("/"))
})
node.removeAttribute(`${INCLUDE_TAG_NAME}`)
await includeHTML(node, {cb})
node.replaceWith(...node.childNodes) // https://stackoverflow.com/a/45657273/9935654
resolve()
}
).catch(err => {
node.innerHTML = `${err.message}`
resolve()
})
})
}
if (cb) {
cb()
}
}
// popup.js
import * as include from "include.js"
window.onload = async () => {
await include.includeHTML(undefined, {})
// ...
}
Ausgabe
<!-- popup.html -->
<head>
<link href="https://.../bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://.../font-awesome/5.15.4/css/all.min.css" />
</head>
<body>
<h2>Hello World</h2>
</body>