1、HTML Imports能实现什么功能?就是在html文件中,引入另一个html文件。如果你熟悉php的话,就知道require、include能引入别的文件。jsp也是有类似的导入其他文件的功能。HTML Imports用于模板功能,还是比较方便的。
2、比较简单直接上代码,准备两个文件:
3、部署到http服务器上,浏览器访问,就可以看到效果了。如图:
4、另外附上完整的代码:【1.html】<!DOCTYPE html><html><head> <罪焐芡拂meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Demo</title> <!-- HTML Imports --> <link href="2.html" rel="import" /></head><body> <div id="container"> </div> <div id="container2"> </div> <script> // 在javascript中调用HTML Imports的内容: var post = document.querySelector('link[rel="import"]').import; console.log(post.body.innerHTML) //能输出对应的html document.querySelector('#container').appendChild(post.querySelector('.header')); // document.querySelector('#container2').innerHTML=post.body.innerHTML; // console.log(post) console.log(post.body.innerHTML) //不能输出对应的html了,仅仅输出一部分 //HTML Imports 貌似有这样的特性:如果你已经把对应的html拼接到别的节点了,那个这个对象上就会删除已经被使用的节点 </script> <p> chrome 版本39.0.2171.95 m测试发现,他已经支持HTML Imports 特性了。(2014-12-29) <br> HTML Imports 的演示demo不要在本地文件系统直接用浏览器打开,请部署到http服务器再用浏览器访问(比如nginx、apache等)。 <br> 本地访问,chrome会报错,因为这样import,chrome认为你跨域了。 <br> chrome报错信息为: <br> Imported resource from origin 'file://' has been blocked from loading by Cross-Origin Resource Sharing policy: Received an invalid response. Origin 'null' is therefore not allowed access. </p></body></html>【2.html】<div class="header"> <ul style="list-style=none;"> <li ><a href="###">导航1</a></li> <li ><a href="###">导航2</a></li> <li ><a href="###">导航3</a></li> </ul></div><div class="test"> </div>