代码之家  ›  专栏  ›  技术社区  ›  VSO

从另一个网站导入<template>元素

  •  2
  • VSO  · 技术社区  · 7 年前

    tl;医生:试图 <template> 元素托管在其他地方,怎么办?


    我有一个 html <head> (重点是它是一个 template 标签):

      <template>
        <style>div{ background-color: red;}</style>
        <div id = "testTemplate">1</div>
      </template>
    

    正如所料,在我将模板附加到某个阴影根之前,此代码不会生成模板,例如:

    <script>
      var template = document.querySelector('template');
      var containerHost = document.querySelector('.containerHost');
      var shadowRoot = containerHost.createShadowRoot();
      shadowRoot.appendChild(document.importNode(template.content, true));
    </script>
    

    当我运行上面的代码时,会显示我的模板。太棒了现在,我正在尝试将我的web组件移动到其他地方托管的网站。所以我创建了一个github页面,我确认了它的效果: https://myusername.github.io/webcomponent/ .

    这是一个完整的html页面,其中包含我的模板(同上)。然后,我尝试使用以下方法将html从github页面拉入html:

      <link rel="import" href="https://myusername.github.io/webcomponent/">
    

    这不会抛出错误,但 <模板(>); 对我的页面不可见,我收到以下错误:

    未捕获的TypeError:无法读取null的属性“content” 在web-component2。html:31

    因为 var template = document.querySelector('template'); 退货 null .

    有什么好处?如何获取模板?

    附笔。 使用此 page as a guide
    从中获取html导入语句 here


    编辑:

    我看到一个请求正在发送到我的站点,并返回一个 304 ,这是回应:

    <html>
    <head>
    
      <template>
        <style>div{ background-color: red;}</style>
        <div id = "testTemplate">1</div>
      </template>
    
    </head>
    <body>
    </body>
    </html>
    

    所以 html < 或者我错过了同样简单的事情。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Pointy    7 年前

    the linked article 关于导入:一旦获取了导入的内容,就必须从 <link> 元素,而不是来自 document :

    function getTemplate(e) {
      let template = e.target.import.querySelector("template");
      shadowRoot.appendChild(document.importNode(template.content, true));
    }
    ...
    
    <link rel=import href="http://what.ever" onload="getTemplate(event)">
    

    例如这个 <链接(>); 元素有一个“import”属性,该属性用作已导入文档的根,然后您可以使用 querySelector() 文件

        2
  •  0
  •   ayushgp    7 年前

    无法从中访问导入的模板 document DOM。您需要获取运行脚本的当前文档,并从中选择模板。例如

    const currentDocument = document.currentScript.ownerDocument;
    // Above is the document in which the script is executing. 
    // Template also resides in this document.
    const template = currentDocument.querySelector('#my-template');
    const instance = template.content.cloneNode(true);
    shadowRoot.appendChild(instance);
    

    也要重新考虑使用HTML导入 deprecated and are likely to be removed from the spec . 考虑使用AJAX请求获取HTML。你可以找到一个例子 here .