大熊君学习html5系列之------History API(SPA单页应用的必备------重构完结版)
一,开篇分析
Hi,大家好!大熊君又和大家见面了,(*^__^*) 嘻嘻……,这系列文章主要是学习Html5相关的知识点,以学习API知识点为入口,由浅入深的引入实例,
让大家一步一步的体会"h5"能够做什么,以及在实际项目中如何去合理的运用达到使用自如,完美驾驭O(∩_∩)O~,好了,废话不多说,直接进入今天的主题,
今天主要讲的是对昨天文章中的代码进行重构,并且相应的美化了一下前台UI界面,如下图所示的效果:
哈哈哈酷吧!继续让咱们做个简单的回顾:
为了提高Web页面的响应速度,越来越多的开发者开始采用单页面结构(single-page application)的解决方案。所谓的单页面结构就是指多个页面间切换时,不刷新当前整个页面,更新页面展示数据,并且相应地改变地址栏中的url,以使用户可以分享这个url。
如果你使用chrome或者firefox等浏览器访问"github.com、plus.google.com"等网站时,细心的你会发现页面之间的点击是通过ajax异步请求的,
同时页面的URL发生了了改变。并且能够很好的支持浏览器前进和后退。是什么有这么强大的功能呢?恩,这就会说到HTML5里引用了新的API:
“history.pushState”和“history.replaceState”
二者之间的重要区别------"window.history.replaceState"和"window.history.pushState"类似,不同之处在于replaceState不会在window.history里新增历史记录点,其效果类似于window.location.replace(url),都是不会在历史记录点里新增一个记录点的。当你为了响应用户的某些操作,而要更新当前历史记录条目的状态对象或URL时,使用replaceState()方法会特别合适。
(二),流程梳理
页面首次载入,虽然我们访问的URL是"http://localhost:8888/bbSPA.html",但是,实际URL确是:
"http://localhost:8888/bbSPA.html#shanghai",”history.replaceState“完成了初始化url切换工作,并且初始做了加载
"shanghai.data"的数据工作,鼠标点击左边的任意一个菜单项,右侧内容是Ajax载入,并且页面的URL随之发生改变,例如,点击北京。
此时,我们点击地址栏的后退按钮,又回到了上海,并且显示内容。原理很简单,就是通过监听”window.onpopstate“,达到了自由切换的作用。
测试时注意事项:
测试需要搭建一个web服务器,以http://host/的形式去访问才能生效,如果你在本地测试以file://这样的方式在浏览器打开,就会出现如下的问题:
|
Uncaught SecurityError: A history state object with URL 'file:///C:/xxx/xxx/xxx/xxx.html' cannot be created in a document with origin 'null' . |
因为你要pushState的url与当前页面的url必须是同源的,而file://形式打开的页面是没有origin的,所以会报这个错误。
(三),重构一下昨天的代码
说明几点:
(1),昨天的代码虽然功能是完成了,但是很松散需要通过类的方式进行有效的组织。
(2),Api要粒度化,各负其责,通过“init”初始化方式进项合理的组织。
(3),UI部分做了修改增强了体验和视觉感。
(4),补充相关数据文件,例如:“beijing.data”,内容如下:
{ "content" : "Hi,这里是北京(*^__^*) 嘻嘻……)!" } |
好了!!!以下是完整代码:
1,html源码
1 <body> 2 <div class="hd">bbSPA测试页面</div> 3 <ul id="list" > 4 <li><a href="#beijing">北京</a></li> 5 <li><a href="#shanghai">上海</a></li> 6 <li><a href="#shenzhen">深圳</a></li> 7 <li><a href="#guangzhou">广州</a></li> 8 <li><a href="#tianjin">天津</a></li> 9 </ul> 10 <div id="content-main"></div> 11 </body>
·2,css源码
1 .hd { 2 height:60px; 3 line-height: 60px; 4 color:#f8f8f8; 5 font-family: "微软雅黑" ; 6 font-size: 24px; 7 text-align: center; 8 background: #49b49b; 9 } 10 #list { 11 border-bottom:2px solid #49b49b; 12 height:32px; 13 width:520px; 14 list-style:none; 15 } 16 #list li { 17 padding:0px; 18 margin-left:10px; 19 width:84px; 20 height:32px; 21 float : left; 22 } 23 #list li a { 24 padding:0px; 25 width:84px; 26 height:32px; 27 line-height: 32px; 28 background: #49b49b; 29 color:#fff; 30 font-family: arial ; 31 font-size: 13px; 32 text-align: center; 33 display:block; 34 text-decoration:none; 35 } 36 #list li a:hover { 37 background: #019875; 38 } 39 #content-main { 40 width:556px; 41 height:220px; 42 border:2px solid #49b49b; 43 }
3,Js源码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | function bbSPA(elem){ this .elem = elem ; } ; var bbSPAProto = bbSPA.prototype ; bbSPAProto.getElem = function (){ return this .elem ; } ; bbSPAProto._getDefaultHash = function (){ return window.location.hash ; } ; bbSPAProto._getCurrentHash = function (){ return this .getElem().eq(1).attr( "href" ) ; } ; bbSPAProto._parseHash = function (hash){ return hash.split( "#" )[1] ; } ; bbSPAProto._fnPopStateHandler = function (target){ var that = this ; var elem = target || null ; var query = this ._getDefaultHash() ; if (!query){ if (elem = this ._getElemByIndex(1)){ this ._addToHistory(elem.attr( "href" ), true ) ; this ._fnPopStateHandler(elem) ; } } else { this .getElem().find( "li a" ).each( function () { if (!elem && $( this ).attr( "href" ) == query){ elem = $( this ) ; } }) ; if (!elem){ this ._fnPopStateHandler( this ._getElemByIndex(1)) ; } else { elem.trigger( "click" ) ; } } } ; bbSPAProto._showContent = function (action){ var that = this ; this ._loadContent( this ._parseHash(action) + ".data" ).done( function (data){ that._renderContent(data[ "content" ]) ; that._addToHistory(action, false ) ; }).fail( function (){ throw new Error( "load content error !" ) ; }) ; } ; bbSPAProto._loadContent = function (url){ return $.ajax({ url : url , dataType : "json" }) ; } ; bbSPAProto._getElemByIndex = function (index){ return this .getElem().find( "li a" ).eq(index) ; } ; bbSPAProto._renderContent = function (text){ this .getElem().next().text(text) ; } ; bbSPAProto._addToHistory = function (hash,noState){ var stateObj = { hash : hash } ; if (noState){ window.history.replaceState(stateObj, "" ,hash) ; } else { window.history.pushState(stateObj, "" ,hash) ; } } ; bbSPAProto._isSupportH5History = function (){ return !!( "pushState" in window.history) ; } ; bbSPAProto.init = function (){ var that = this ; if (! this ._isSupportH5History()){ throw new Error( "Not Support H5 History API !" ) ; } this .getElem().on( "click" , "a" , function (){ that._showContent($( this ).attr( "href" )) ; return false ; }) ; window.addEventListener( "popstate" , function (){ that._fnPopStateHandler() ; }, false ) ; this ._fnPopStateHandler() ; } ; |
(四),最后总结
(1),理解History Api的使用方式以及具体实例中使用的目的是为了解决哪些问题。
(2),两个核心Api的不同之处在哪。
(3),想想重构后与之前有什么优势,以及是否可以进一步抽象出不同的类,比如“Router”,“History”。
(4),说几句:编程是思想层面的事,实现方式很多,关键是看问题的深度与角度,好了不罗嗦了!!!明天继续!
哈哈哈,本篇结束,未完待续,希望和大家多多交流够沟通,共同进步。。。。。。呼呼呼……(*^__^*)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?