html - 我可以通过缓存动态加载 Web 组件引用的数据吗?

标签 html caching web-component browser-cache

我目前正在学习 Web 组件,我想知道是否可以让组件动态加载自己的数据,类似于 <img>从它的src做起属性,即类似这样的内容:

<my-fancy-thingy src='/stuff.json'></my-fancy-thingy>

显然,如果stuff.json,此功能会很有用。可能相当大,因此还应该可以利用浏览器的缓存机制,这样引用的文件就不会在我们每次请求页面时重新加载,除非发生更改。

这可以做到吗?

最佳答案

当然,从 中获取灵感,请参阅 Dev.to Post

/*
  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/

相关文章:

php require 方法不会显示 css 样式

javascript - 移动时将三 Angular 形点对准圆心

laravel 5.5 缓存错误 "Serialization of ' 不允许关闭”

django - nginx 缓存,staticgenerator 与 memcached

javascript - 扩展 Web 组件中的 HTML 元素

html - CSS 设置高度和宽度,但在 flexbox 中调整 div 大小

html - Angular2 - 动态添加 HTML 属性和类

java - 集群环境下的应用程序可以写缓存吗?

html - Polymer 中的自定义属性不起作用

javascript - 扩展原生 DOM 元素的简写?