分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

Web Component

发布时间:2023-09-06 02:27责任编辑:郭大石关键词:Web

前言

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

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved