TYPECHO启用全站PJAX

LeslieLin 编程技术
阅读量 0 评论量 0

How to start

引用公共库

<script src="https://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>(已引入JQUERY请忽略)
<script src="https://cdn.bootcss.com/jquery.pjax/2.0.1/jquery.pjax.js"></script>

定义一个ID给DIV容器包裹你要PJAX的页面,如

<div id='pjax'>
</div>

再在footer.php调用PJAX(放于JQUERY之后)

<script>
//获取网站当前域名
function getBaseUrl() {
  var ishttps = 'https:' == document.location.protocol ? true : false;
  var url = window.location.host;
  if (ishttps) {
    url = 'https://' + url;
  } else {
    url = 'http://' + url;
  }
  return url;
}
let url = '"'+getBaseUrl()+'"';
$(document).pjax('a[href^='+ url +']:not(a[target="_blank"], a[no-pjax])', {
  container: '#pjax',//DIV容器的ID
  fragment: '#pjax',//作为整个pjax框架,必须写上
  timeout: 8000 //超时就会被迫页面就会完全刷新,单位毫秒
})
</script>

加载动画

动画我用的是nprogress
引入js和css(JQUERY一定要先加载):

<link rel='stylesheet' href='https://unpkg.com/nprogress@0.2.0/nprogress.css'/> 这个我是放在header
<script src='//unpkg.com/nprogress@0.2.0/nprogress.js'></script>放在footer

然后加入代码

$(document).on('pjax:start', function() { NProgress.start(); });
$(document).on('pjax:end',   function() { NProgress.done(); });

完整代码

function getBaseUrl() {
  var ishttps = 'https:' == document.location.protocol ? true : false;
  var url = window.location.host;
  if (ishttps) {
    url = 'https://' + url;
  } else {
    url = 'http://' + url;
  }
  return url;
}
let url = '"'+getBaseUrl()+'"';
$(document).pjax('a[href^='+ url +']:not(a[target="_blank"], a[no-pjax])', {
  container: '#pjax',
  fragment: '#pjax',
  timeout: 8000
})
$(document).on('pjax:start',function() { NProgress.start(); });
$(document).on('pjax:end',function() { NProgress.done(); });
if(typeof lazyload === "function") {
  $(document).on('pjax:complete', function () {
    jQuery(function() {
      jQuery("div").lazyload({effect: "fadeIn"});
    });
    jQuery(function() {
      jQuery("img").lazyload({effect: "fadeIn"});
    });
  });
}else{
  console.log('lazyload is closed');
}
喵~