【发布时间】:2020-10-06 20:27:48
【问题描述】:
我想重用我的包含一些 javascript 代码的 html 组件,所以为了简化我举一个简单的例子:
index.html:
<!DOCTYPE html>
<html>
<head></head>
<body>
<my-component></my-component>
<script src="index.js"></script>
</body>
</html>
my-component.html:
<template>
<div id="something"></div>
<script>
// It doesn't work, this here is "window"
document.getElementById("something").innerHTML = "Something"
</script>
</template>
index.js:
window.makeComponent = (function () {
function fetchAndParse(url) {
return fetch(url, {mode: "no-cors"})
.then(res => res.text())
.then(html => {
const parser = new DOMParser()
const document = parser.parseFromString(html, 'text/html')
const head = document.head
const template = head.querySelector('template')
return template
})
}
function defineComponent(name, template) {
class UnityComponent extends HTMLElement {
connectedCallback() {
const shadow = this.attachShadow({mode: 'open'})
shadow.appendChild(document.importNode(template.content, true))
}
}
return customElements.define(name, UnityComponent)
}
function loadComponent (name, url) {
fetchAndParse(url).then((template) => defineComponent(name, template))
}
return {loadComponent}
}())
makeComponent.loadComponent("my-component", "my-component.html")
我可以使用这段代码,但是它将脚本的所有变量复制到窗口:
<template>
<div id="something"></div>
<style onload="templFunc.apply(this.getRootNode())"></style>
<script>
function templFunc() {
// It works
let text = "Something"
this.querySelector('#something').innerHTML = text
// but...
console.log(window.text) // => "Something"
}
</script>
</template>
没有意义,如果脚本在模板内至少应该可以访问模板内的元素,否则模板几乎不能用于javascript,所以,我无法理解的意图在模板里面使用脚本或者如何复用使用javascript的web组件,这样做有错吗?
那么,如何在不将所有脚本变量复制到窗口的情况下访问模板内脚本中的组件?
【问题讨论】:
-
您可以将索引文件设为 php 并包含或需要其中的组件。
-
我没有使用 php。
标签: javascript html web-component shadow-dom