码迷,mamicode.com
首页 > Web开发 > 详细

Web Component

时间:2018-12-24 02:53:10      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:iframe   节点   ons   body   嵌套   功能   doc   文件的   没有   

前言

Web Component不是新东西,几年前的技术,但是受限于浏览器兼容性,一直没有大规模应用在项目里,直到现在(2018年年末),除IE仍不支持之外,其它主流浏览器都支持Web Component。

Web Component不是一个东西,它分为四部分,分别是

template——模板
HTML import——HTML导入
Shadow DOM——影子DOM
Custom Elements——自定义元素

template

前端模板也不是个新概念,templatejs、ejs等模板引擎早就将模板的概念深入人心,在纯HTML世界里,我们通常把模板写在script标签里,将type改为text/html,避免浏览器解析,像这样

<script type="text/html">
    <div>
        <title>标题</title>
        <content>内容</content>
    </div>
</script>   

template则是用标签包裹模板内容,不同之处在于获取模板内容的方式,script模板是通过获取script的innerHTML来获取,template则是获取读取template节点的content属性来获取

// 模板文件
<template>
    <div>
        <title>标题</title>
        <content>内容</content>
    </div>
</template>
// 获取模板内容
console.log(document.querySelector('template').content);

HTML import

在此之前,HTML导入一般用iframe嵌套或依赖后端又或是其他库,HTML import为原生HTML提供了导入HTML文件的功能,使用link标签,rel设置为import,href为被导入文件路径

<link rel="import" href="header.html">

HTML导入之后不会立即被浏览器解析并渲染,需要手动插入到DOM节点,这点跟css不同

// header.html
<h2 id="header">这是公共header</h2>
<h2 id="footer">这是公共footer</h2>


// index.html
<html>
    <head>
        <link rel="import" href="header.html">
    </head>
    <body>
        <content>内容区</content>
        <script type="text/javascript">
            let importDom = document.querySelector('link[href="header.html"]').import;
            let content = document.querySelector('content');
            let header = importDom.querySelector('#header');
            let footer = importDom.querySelector('#footer');

            document.body.insertBefore(header, content);
            document.body.appendChild(footer);
        </script>
    </body>
</html>

最终渲染结果

这是公共header

内容区

这是公共footer

Web Component

标签:iframe   节点   ons   body   嵌套   功能   doc   文件的   没有   

原文地址:https://www.cnblogs.com/wangmeijian/p/10061647.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!