我目前正在学习 Web 组件,我想知道是否可以让组件动态加载自己的数据,类似于 <img>
从它的src
做起属性,即类似这样的内容:
<my-fancy-thingy src='/stuff.json'></my-fancy-thingy>
显然,如果stuff.json
,此功能会很有用。可能相当大,因此还应该可以利用浏览器的缓存机制,这样引用的文件就不会在我们每次请求页面时重新加载,除非发生更改。
这可以做到吗?
最佳答案
当然,从
/*
defining the <load-file> Web Component,
yes! the documenation is longer than the code
License: https://unlicense.org/
*/
customElements.define("load-file", class extends HTMLElement {
// declare default connectedCallback as sync so await can be used
async connectedCallback(
// attach a shadowRoot if none exists (prevents displaying error when moving Nodes)
// declare as parameter to save 4 Bytes: 'let '
shadowRoot = this.shadowRoot || this.attachShadow({mode:"open"})
) {
// load SVG file from src="" async, parse to text, add to shadowRoot.innerHTML
shadowRoot.innerHTML = await (await fetch(this.getAttribute("src"))).text()
// append optional <tag [shadowRoot]> Elements from inside <load-svg> after parsed <svg>
shadowRoot.append(...this.querySelectorAll("[shadowRoot]"))
// if "replaceWith" attribute
// then replace <load-svg> with loaded content <load-svg>
// childNodes instead of children to include #textNodes also
this.hasAttribute("replaceWith") && this.replaceWith(...shadowRoot.childNodes)
}
})
将 .text()
更改为 .json()
并解析 JSON 文件
可以通过将字符串存储在 localStorage 中来完成缓存(但我认为总共限制为 5MB):
你需要想出“数据已经改变”的策略;因为客户端不知道数据何时实际发生更改。也许是一个额外的信号量文件/端点,可以在(大)JSON文件被更改时提供信息。
关于html - 我可以通过缓存动态加载 Web 组件引用的数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67803434/