香草web组件结构



我正在寻找构建香草web组件。我以前使用过聚合物,喜欢这样一个事实:你可以在一个文件中为你的组件拥有模板、样式和JavaScript。如果可能的话,我想用"香草"web组件实现这一点,但无法解决如何。我已经从这里采取的代码,并将其添加到一个文件,我使用如下:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <title>Component test</title>
    
    <link rel="import" href="x-foo-from-template.html">
  </head>
  <body>
    <x-foo-from-template></x-foo-from-template>
  </body>
</html>

这个失败是因为当我们尝试选择模板时,它不存在,因为此时模板不在DOM中(对吗?)

有办法做到这一点吗?我个人更喜欢使用document.createElement在JavaScript中创建HTML的方法。

从导入的文档中获取模板有两种主要方法:

1。<link>元素的import性质

<link rel=import>元素拥有包含导入文档的import属性。你可以对它执行querySelector调用来获取<template>:

var doc = document.querySelector( 'link[href$="x-foo-from-template.html"]').import
var template = doc.querySelector( 'template' )

然后使用importNode()cloneNode()将模板导入自定义元素(或其Shadow DOM)。


2。来自currentScript

ownerDocument属性

当一个脚本被解析时,全局值document.currentScript引用被解析的脚本,因此它的属性ownerDocument是对拥有该脚本的文档的引用。你可以对它执行querySelector调用:

var template = document.currentScript.ownerDocument.querySelector( 'template' )

注意: currentScript值被临时设置为,因此它在后续调用(如connectedCallback()attachedCallback())中将不再工作,因此您必须在解析时将其记在持久变量中,以便在以后需要时重用。

后来者:

截至2021年,HTML导入功能已被弃用(MDN Link)。

我不推荐这样做,你可以用一个data-属性来创建一个模板标签来导入html。编写一个脚本,在所有具有该属性的元素上运行,并在脚本中使用fetch()访问这些html部分,将获取的导入添加到模板标记并使用它,例如:template.content.cloneNode( true ) .

最新更新