首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当托管在与应用程序本身不同的域上时,如何获取web组件的HTML和CSS文件?

当托管在与应用程序本身不同的域上时,如何获取web组件的HTML和CSS文件?
EN

Stack Overflow用户
提问于 2021-10-02 00:57:46
回答 2查看 922关注 0票数 2

我正在寻找一个干净的解决方案,将web组件拆分为JS、HTML和CSS文件,并将它们保存在CDN上。我试图避免webpack html和css-加载程序,因为他们不允许我导出我的web组件作为一个普通的ES模块。

我们的目标是使用任何前端应用程序中的web组件,只需从一个加密的URL中导入它。因此,应保留对关切的分离。用于样式、标记和逻辑的单个文件也允许语法突出显示。

在本地开发环境中,我发现以下内容非常有用:

WebComponent.js:

代码语言:javascript
复制
export default class WebComponent extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });

    const style = new CSSStyleSheet();
    const template = document.createElement("template");

    fetch("./WebComponent.css").then((res) =>
      res.text().then((css) => {
        style.replaceSync(css);
        this.shadowRoot.adoptedStyleSheets = [style];
      })
    );

    fetch("./WebComponent.html").then((res) =>
      res.text().then((html) => {
        template.innerHTML = html;
        this.shadowRoot.appendChild(template.content.cloneNode(true));
      })
    );
  }
}

WebComponent.css:

代码语言:javascript
复制
button {
    /* Some styling */
}

WebComponent.html:

代码语言:javascript
复制
<button>Custom buttom</button>

我可以通过使用浏览器本机ES模块导入组件:

index.html:

代码语言:javascript
复制
<!DOCTYPE html>
<html>
  <body>
    <web-component></web-component>

    <script type="module">
      import WebComponent from "./WebComponent";
      customElements.define("web-component", WebComponent);
    </script>
  </body>
</html>

直到我将web组件文件移动到与我的index.html不同的位置(谷歌云存储桶),并从那里导入index.html,这才能奏效。

代码语言:javascript
复制
<!DOCTYPE html>
<html>
  <body>
    <web-component></web-component>

    <script type="module">
      import WebComponent from "https://storage.googleapis.com/storage-bucket/WebComponent.js";
      customElements.define("web-component", WebComponent);
    </script>
  </body>
</html>

WebComponent.js被正确导入,但是它尝试从相对于服务index.htmllocalhost的URL中获取WebComponent.cssWebComponent.html。但是,它应该从相对于托管位置(https://storage.googleapis.com/storage-bucket/)的URL中获取。

有什么办法可以实现这样的事情吗?无需将url硬编码到两个提取调用中。这不是一个选项,因为url可以不时自动更改。

EN

回答 2

Stack Overflow用户

发布于 2021-10-08 16:49:44

您对JS网页中的资源链接存在问题,其中:

"./WebComponent";

  • 本地组件正在运行
    • 导入WebComponent

"URL";

  • 远程组件的
    • 导入WebComponent失败

也许要想让它起作用,您应该尝试以下几种方法:

代码语言:javascript
复制
<script type="module" src="https://storage.googleapis.com/storage-bucket/WebComponent.js">
      customElements.define("web-component", WebComponent);
</script>

参考资料:

票数 0
EN

Stack Overflow用户

发布于 2021-10-11 17:39:02

JavaScript文件路径相对于显示的页面。所以你所观察到的行为是预料之中的。

您可以在下面的简单js声明中使用JavaScript变量,并且每当动态分配URL时都可以使用该变量:

代码语言:javascript
复制
<script type="text/javascript">
   var webComponentPath = 'https://storage.googleapis.com/storage-bucket/';
</script>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69413201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档