InstantClick是一个JavaScript小库,可以显著提高网站链接跳转的速度。它使用了pjax技术,将网站改变成了一个web应用,使链接跳转的时候没有闪烁感,提高了网站的浏览体验。本文记录我折腾InstantClick的过程。

I. 为什么要使用InstantClick

InstantClick官网上这样说到:尽管现在带宽越来越高,但是web浏览的速度并没有显著提高,归根结底是因为网页加载的延迟导致的。所以InstantClick号称可以提前网页加载200ms到300ms。原理就是,在用户鼠标移入链接的时候就开始使用pushState和Ajax技术(pjax)替换网页的body和title内容,并更新地址栏链接。这样做巧妙地把鼠标移入链接到鼠标点击并放开的这段时间用于网页的请求和加载。通常这段时间足够网页内容的请求,所以往往在用户松开鼠标那一刻,网页已经加载完毕。并且由于整个过程没有刷新页面,网页不会有任何闪烁,并且InstantClick内置了一个加载进度条,可以显著提高用户体验。

II. 下载InstantClick

去InstantClick官网的下载页面下载instantclick.js或者instantclick.min.js(压缩版才2.7kb),放在Typecho正在应用的主题文件夹下。

III. 使用InstantClick

InstantClick封装得很好,所以只要在页面里面引入instantclick.js并运行。我通常都是在</body>之前引用JavaScript脚本。所以在Typecho中的主题文件夹下找到footer.php文件并把以下代码添加到</body>之前就行了。

<!-- 引入instantClick.js快速响应插件 -->
<script src="<?php $this->options->themeUrl('./js/instantclick.js'); ?>"></script>
<script data-no-instant>InstantClick.init();</script>

IV. 设置InstantClick

默认情况下,InstantClick在载入页面的时候,会在页面的顶部显示一个进度条,可以在CSS里面更改颜色:

#instantclick-bar {
    background: white;
}

也可以隐藏进度条:

#instantclick {
    display: none;
}

V. 可能会导致的问题

  1. 有些JavaScript脚本运行失败。若网页有其它脚本引用在<head>标签里面,可能会运行失败,因为InstantClick替换里body里面的所有内容,原来的脚本绑定的DOM内容可能会失效。解决办法是将原脚本移到</body>之前。
  2. 有些网站统计工具可能会失效。由于instantclick不会重新运行位于head部分的JavaScript代码,而很多工具性软件,比如MathJax、百度统计、Google Analytics、Google Code Prettify等软件都是直接将JS文件插入到head区域。这导致这些工具在instantclick点击后失效,需要重新配置。
    配置并不复杂,这些工具本身的代码不用做任何修改,该怎么放还怎么放。但在InstantClick.init();之前添加以下代码:
<script data-no-instant>
InstantClick.on('change', function(isInitialLoad) {
  if (isInitialLoad === false) {
    if (typeof MathJax !== 'undefined') // support MathJax
      MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
    if (typeof prettyPrint !== 'undefined') // support google code prettify
      prettyPrint();
    if (typeof _hmt !== 'undefined')  // support 百度统计
      _hmt.push(['_trackPageview', location.pathname + location.search]);
    if (typeof ga !== 'undefined')  // support google analytics
        ga('send', 'pageview', location.pathname + location.search);
  }
});
InstantClick.init();
</script>
  1. 网站无法正常登陆和退出。这是因为网站登录通常会更换网站模板,比如从前台登录到后台,往往网站的结构会变化,这时候区域的脚本和样式都已经不适用与当前页面。解决办法InstantClick官网也给出了,就是给这些链接添加到黑名单里。具体方法是给不用InstantClick进行跳转的链接加一个data-no-instant属性。在Typecho里面,负责登录的链接在sidebar.php里面,所以找到“进入后台”、“登录”和“退出”这三个链接并加上data-no-instant即可。
<!-- 把登录等功能的链接加入黑名单 -->
<?php if($this->user->hasLogin()): ?>
    <li class="last"><a href="<?php $this->options->adminUrl(); ?>" data-no-instant><?php _e('进入后台'); ?> (<?php $this->user->screenName(); ?>)</a></li>
    <li><a href="<?php $this->options->logoutUrl(); ?>" data-no-instant><?php _e('退出'); ?></a></li>
<?php else: ?>
    <li class="last"><a href="<?php $this->options->adminUrl('login.php'); ?>" data-no-instant><?php _e('登录'); ?></a></li>
<?php endif; ?>

 

via。http://zhouzhengsheng.com/archives/50/ 

 

关于typecho评论失效 可以看这个 https://github.com/typecho/typecho/issues/324

 

关闭掉后台设置->评论里的反垃圾选项

最后修改:2017 年 06 月 08 日 07 : 59 PM