关于前端原生开发 页面组件化开发 html页面引入另一个html页面

您所在的位置:网站首页 html引入公共页面 关于前端原生开发 页面组件化开发 html页面引入另一个html页面

关于前端原生开发 页面组件化开发 html页面引入另一个html页面

2024-07-08 22:13| 来源: 网络整理| 查看: 265

我们在使用代码编程一个网站的时候,通常情况下头部和尾部是相同的,如果一个网站的每个页面都把这些代码写一遍,不仅浪费时间,还显得重复代码很多,所以此时把重复的页面单独摘出来,在用到的时候从外部直接引进去,就能节省很多时间,减少很多代码。

在这里,有好几种引入html文件的方式,不过每种都是有利有弊,需要根据需要自行选择 有大佬反馈解决了有些浏览器本地实现不了的问题:放到服务器上面!(感谢!!!)

link标签介绍

link标签通常放置在一个网页的头部标签head标签内的用于链接外部css文件、链接收藏夹图标(favicon.ico), 标签最常见的用途是链接外部样式表,外部资源。

//引入css样式 //ICO图标引人代码如下: 方法一 使用import引入(《head》中引入文件,《script》中加载内容)

href链接引入的html文件,id可以看做页面引导,在script中用到

主页面 document.write(page1.import.body.innerHTML); 你好呀! document.write(page2.import.body.innerHTML);

在这里插入图片描述 由上图可以看出,import引入除开script标签,在其他html body中写入什么就引入什么,完全的内容格式.

方法二 JQ引入 你好,我在中间! //在js中引入 $(document).ready(function () { $('.top').load('top.html'); $('.footer').load('fotter.html'); });

使用js引入,相当于把引入的html中head和body标签中的数据拖出来,在外面包了一个你自己写的标签,比如说上面代码中的

运行结果同import相同,这里不再展示

注意:是head和body标签中的数据,不带标签,下图是浏览器显示代码 在这里插入图片描述

方法三 include 引入(涉及到一个从网上扒的封装函数,下面有)(head和body标签中的数据直接引入) 你没有看错,我在这!

在这里插入图片描述

include.js压缩代码:

(function(window,document,undefined){var Include39485748323=function(){};Include39485748323.prototype={forEach:function(array,callback){var size=array.length;for(var i=size-1;i>=0;i-=1){callback.apply(array[i],[i])}},getFilePath:function(){var curWwwPath=window.document.location.href;var pathName=window.document.location.pathname;var localhostPaht=curWwwPath.substring(0,curWwwPath.indexOf(pathName));var projectName=pathName.substring(0,pathName.substr(1).lastIndexOf('/')+1);return localhostPaht+projectName},getFileContent:function(url){var ie=navigator.userAgent.indexOf('MSIE')>0;var o=ie?new ActiveXObject('Microsoft.XMLHTTP'):new XMLHttpRequest();o.open('get',url,false);o.send(null);return o.responseText},parseNode:function(content){var objE=document.createElement("div");objE.innerHTML=content;return objE.childNodes},executeScript:function(content){var mac=/([\s\S]*?)/g;var r="";while(r=mac.exec(content)){eval(r[1])}},getHtml:function(content){var mac=/([\s\S]*?)/g;content.replace(mac,"");return content},getPrevCount:function(src){var mac=/\.\.\//g;var count=0;while(mac.exec(src)){count+=1}return count},getRequestUrl:function(filePath,src){if(/http:\/\//g.test(src)){return src}var prevCount=this.getPrevCount(src);while(prevCount--){filePath=filePath.substring(0,filePath.substr(1).lastIndexOf('/')+1)}return filePath+"/"+src.replace(/\.\.\//g,"")},replaceIncludeElements:function(){var $this=this;var filePath=$this.getFilePath();var includeTals=document.getElementsByTagName("include");this.forEach(includeTals,function(){var src=this.getAttribute("src");var content=$this.getFileContent($this.getRequestUrl(filePath,src));var parent=this.parentNode;var includeNodes=$this.parseNode($this.getHtml(content));var size=includeNodes.length;for(var i=0;i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3