深入探究HTML5的History API

   2015-08-09 0
核心提示:这篇文章主要介绍了深入探究HTML5的History API,重点讲述了HTML5中新的方法history.pushState()和history.replaceState(),需要的朋友可以参考下

History是有趣的,不是吗?在之前的HTML版本中,我们对浏览历史记录的操作非常有限。我们可以来回使用可以使用的方法,但这就是一切我们能做的了。

  但是,利用HTML 5的History API,我们可以更好的控制浏览器的历史记录了。例如:我们可以添加一条记录到历史记录的列表中,或者在没有刷新时,可以更新地址栏的URL。
  为什么介绍History API ?

  在这篇文章中,我们将了解HTML 5中History API的来源。在此之前,我们经常使用散列值来改变页面内容,特别是那些对页面特别重要的内容。因为没有刷新,所以对于单页面应用,改变其URL是不可能的。此外,当你改变URL的散列值值,它对浏览器的历史记录没有任何影响。

  然后,现在对于HTML 5的History API来说,这些都是可以轻易实现的,但是由于单页面应用没必要使用散列值,它可能需要额外的开发脚本。它也允许我们用一种对SEO友好的方式建立新应用。此外,它能减少带宽,但是该怎么证明呢?

  在文章中,我将用History API开发一个单页应用来证明上述的问题。

  这也意味着我必须先在首页加载必要的资源。现在开始,页面仅仅加载需要的内容。换句话说,应用并不是一开始就加载了全部的内容,在请求第二个应用内容时,才会被加载。

  注意,您需要执行一些服务器端编码只提供部分资源,而不是完整的页面内容。
  浏览器支持

  在写这篇文章的时候,各主流浏览器对History API的支持是非常不错的,可以点击此处查看其支持情况,这个链接会告诉你支持的浏览器,并使用之前,总有良好的实践来检测支持的特定功能。

  为了用变成方式确定浏览器是否支持这个API,可以用下面的一行代码检验:
 

XML/HTML Code复制内容到剪贴板
  1. return !!(window.history && history.pushState);  

  此外,我建议参考一下这篇文章:Detect Support for Various HTML5 Features.(ps:后续会翻译)

  如果你是用的现代浏览器,可以用下面的代码:
 

XML/HTML Code复制内容到剪贴板
  1. if (Modernizr.history) {   
  2.     // History API Supported   
  3. }  

  如果你的浏览器不支持History API,可以使用history.js代替。
  使用History

  HTML 5提供了两个新方法:

  1、history.pushState();                2、history.replaceState();

  两种方法都允许我们添加和更新历史记录,它们的工作原理相同并且可以添加数量相同的参数。除了方法之外,还有popstate事件。在后文中将介绍怎么使用和什么时候使用popstate事件。

  pushState()和replaceState()参数一样,参数说明如下:

  1、state:存储JSON字符串,可以用在popstate事件中。

  2、title:现在大多数浏览器不支持或者忽略这个参数,最好用null代替

  3、url:任意有效的URL,用于更新浏览器的地址栏,并不在乎URL是否已经存在地址列表中。更重要的是,它不会重新加载页面。

  两个方法的主要区别就是:pushState()是在history栈中添加一个新的条目,replaceState()是替换当前的记录值。如果你还对这个有迷惑,就用一些示例来证明这个区别。

  假设我们有两个栈块,一个标记为1,另一个标记为2,你有第三个栈块,标记为3。当执行pushState()时,栈块3将被添加到已经存在的栈中,因此,栈就有3个块栈了。

  同样的假设情景下,当执行replaceState()时,将在块2的堆栈和放置块3。所以history的记录条数不变,也就是说,pushState()会让history的数量加1.

  比较结果如下图:
深入探究HTML5的History API

到此,为了控制浏览器的历史记录,我们忽略了pushState()和replaceState()的事件。但是假设浏览器统计了许多的不良记录,用户可能会被重定向到这些页面,或许也不会。在这种情况下,当用户使用浏览器的前进和后退导航按钮时就会产生意外的问题。

  尽管当我们使用pushState()和replaceState()进行处理时,期待popstate事件被触发。但实际上,情况并不是这样。相反,当你浏览会话历史记录时,不管你是点击前进或者后退按钮,还是使用history.go和history.back方法,popstate都会被触发。

  In WebKit browsers, a popstate event would be triggered after document’s on load event, but Firefox and IE do not have this behavior.(在WebKit浏览器中,popstate事件在document的on load事件后触发,Firefox和IE没有这种行为)。
  Demo示例

  HTML:
 

XML/HTML Code复制内容到剪贴板
  1. <div class="container">  
  2.     <div class="row">  
  3.         <ul class="nav navbar-nav">  
  4.             <li><a href="home.html" class="historyAPI">Home</a></li>  
  5.             <li><a href="about.html" class="historyAPI">About</a></li>  
  6.             <li><a href="contact.html" class="historyAPI">Contact</a></li>  
  7.         </ul>  
  8.     </div>  
  9.     <div class="row">  
  10.         <div class="col-md-6">  
  11.             <div class="well">  
  12.                 Click on Links above to see history API usage using <code>pushState</code> method.   
  13.             </div>  
  14.         </div>  
  15.         <div class="row">      
  16.             <div class="jumbotron" id="contentHolder">  
  17.                 <h1>Home!</h1>  
  18.                 <p>Lorem Ipsum is simply dummy text of the <span style="width: auto; height: auto; float: none;" id="5_nwp"><a style="text-decoration: none;" mpid="5" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=f7cb547a6e640f0a&k=printing&k0=printing&kdi0=0&luki=5&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=a0f646e7a54cbf7&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F5360%2Ehtml&urlid=0" id="5_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">printing</span></a></span> and typesetting industry.</p>  
  19.             </div>  
  20.         </div>  
  21.     </div>  
  22. </div>  

  JavaScript

XML/HTML Code复制内容到剪贴板
  1. <script type="text/<span style="width: auto; height: auto; float: none;" id="1_nwp"><a style="text-decoration: none;" mpid="1" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=f7cb547a6e640f0a&k=javascript&k0=javascript&kdi0=0&luki=8&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=a0f646e7a54cbf7&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F5360%2Ehtml&urlid=0" id="1_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">javascript</span></a></span>">  
  2.     jQuery('document').ready(function(){   
  3.              
  4.         jQuery('.historyAPI').on('click', function(e){   
  5.             e.preventDefault();   
  6.             var href = $(this).attr('href');   
  7.                  
  8.             // Getting Content   
  9.             getContent(href, true);   
  10.                  
  11.             jQuery('.historyAPI').removeClass('active');   
  12.             $(this).<span style="width: auto; height: auto; float: none;" id="2_nwp"><a style="text-decoration: none;" mpid="2" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=f7cb547a6e640f0a&k=add&k0=add&kdi0=0&luki=3&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=a0f646e7a54cbf7&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F5360%2Ehtml&urlid=0" id="2_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">add</span></a></span>Class('active');   
  13.         });   
  14.              
  15.     });   
  16.          
  17.     // Adding popstate event listener to handle browser back button    
  18.     window.addEventListener("popstate", function(e) {   
  19.              
  20.         // Get State value using e.state   
  21.         getContent(location.pathname, false);   
  22.     });   
  23.          
  24.     function getContent(url, addEntry) {   
  25.         $.get(url)   
  26.         .done(function( <span style="width: auto; height: auto; float: none;" id="3_nwp"><a style="text-decoration: none;" mpid="3" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=f7cb547a6e640f0a&k=data&k0=data&kdi0=0&luki=6&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=a0f646e7a54cbf7&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F5360%2Ehtml&urlid=0" id="3_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">data</span></a></span> ) {   
  27.                  
  28.             // Updating Content on Page   
  29.             $('#contentHolder').html(data);   
  30.                  
  31.             if(<span style="width: auto; height: auto; float: none;" id="4_nwp"><a style="text-decoration: none;" mpid="4" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=f7cb547a6e640f0a&k=add&k0=add&kdi0=0&luki=3&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=a0f646e7a54cbf7&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F5360%2Ehtml&urlid=0" id="4_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">add</span></a></span>Entry == true) {   
  32.                 // Add History Entry using pushState   
  33.                 history.pushState(null, null, url);   
  34.             }   
  35.                  
  36.         });   
  37.     }   
  38. </script>  

  总结(ps:喜欢这两个字~~~^_^~~~)

  HTML 5中的History API 对Web应用有着很大的影响。为了更容易的创建有效率的、对SEO友好的单页面应用,它移除了对散列值的依赖。

 
标签: HTML5 History
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • html5 Canvas 如何自适应屏幕大小
    但是这样创建出的画布不能随着浏览器窗口大小的改变而动态的改变画布的大小。而这一点往往又非常重要, 因为我们会经常改变浏览器窗口大小,不会一直保持某个固定的大小。 html代码 canvas width="300" height="300" id="myCanvas"/canvas设置样式 * {
    03-08
  • html5 中meta中 content=width=device-width注
    !DOCTYPE html        html        head        meta http-equiv="content-type" content="text/html; charset=UTF-8"        meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0"        sty
    03-08
  • HTML5] html和css的使用方法以及样式
    第一步: 清除默认样式第二步: 划分模块第三步: 设置模块的大小以及位置第四步: 划分下一级模块html和css引入网页头像link rel="shortcut icon" href="img/...ico"css样式表的引入方式css样式表的引入方式1、外链式link href="" rel="stylesheet"2、嵌入式
    03-08
  • html5 CSS input placeholder兼容性处理
    1.HTML5对Web Form做了许多增强,比如input新增的type类型、Form Validation等。Placeholder是HTML5新增的另一个属性,当input或者textarea设置了该属性后,该值的内容将作为灰字提示显示在文本框中,当文本框获得焦点时,提示文字消失。以前要实现这效果都是
    03-08
  • HTML5 script 标签的 crossorigin 和integrity
    Bootstrap 4 依赖的基础库中出现了两个新的属性1 script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"/script2 script s
    03-08
  • HTML5 Canvas 绘制斜线
    HTML5 Canvas 绘制斜线
     !DOCTYPE HTMLhtmltitleCanvas直线/titlebodycanvas 您的浏览器不支持 Canvas/canvasscript type="text/javascript"var c = document.getElementById("myCanvas");var cxt = c.getContext("2d");cxt.beginPath();cxt.moveTo(70,140);cxt.lineTo(140,70)
    03-08
  • HTML5 Canvas 画圆【每日一段代码4】
    HTML5 Canvas 画圆【每日一段代码4】
    !DOCTYPE HTMLhtmlbodycanvas ;cxt.beginPath();cxt.arc(100,100,30,0,Math.PI*2,true);cxt.closePath();cxt.fill();/script/body/html显示图: 【画圆,Math.PI 函数的应用。cxt.arc(100,100,30,0,Math.PI*2,true); 括号内第一个和第二个参数,代表圆心坐标
    03-08
  • html5 css3 新元素简单页面布局
    html5 css3 新元素简单页面布局
    【html 代码】!Doctype htmlhtmlhead meta charset="gb2312"titleHMTL5/title link rel="stylesheet" href="html5.css"/headbody header h1脆梨网/h1 h4邪恶漫画专家!/h4 h2邪恶小漫画/h2 /headerdiv关于/a /navsection article header h1Article Header/h1 /
    03-08
  • 微信开发之移动手机WEB页面(HTML5)Javascript实
    在做一个微信的微网站中的一个便民服务电话功能的应用,用到移动web页面中列出的电话号码,点击需要实现调用通讯录,网页一键拨号的拨打电话功能。如果需要在移动浏览器中实现拨打电话,发送email,美国服务器,调用sns等功能,移动手机WEB页面(HTML5)Javascr
    03-08
  • flash传值给javascript,并在html页面输出 flash
    AS里面这样写:getURL("javascript:getval('"+变量+"')"); html里面这样写:script language="javascript" function getval(str) {// url是全局变量,函数正确执行alert("获取的值为:"+str); }/script
    03-08
点击排行