typecho博客实现pjax

Author Avatar
云璃 2018年05月07日

pjax

pjax is a jQuery plugin that uses ajax and pushState to deliver a fast browsing experience with real permalinks, page titles, and a working back button.

pjax works by fetching HTML from your server via ajax and replacing the content of a container element on your page with the loaded HTML. It then updates the current URL in the browser using pushState. This results in faster page navigation for two reasons:

No page resources (JS, CSS) get re-executed or re-applied;
If the server is configured for pjax, it can render only partial page contents and thus avoid the potentially costly full layout render.

Usage:defunkt/jquery-pjax

安装

npm

$ npm install jquery
$ npm install jquery-pjax

standalone script

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<!--
  1.jquery.min.js需在jquery.pjax.js前面引入;
  2.在模版的header.php或footer.php均可引入;
-->
<script src="https://cdn.bootcss.com/jquery.pjax/2.0.1/jquery.pjax.js"></script>

使用

footer.php里面加上这段代码就初步成功。【继续往下看!尤其是 container 的介绍】

<script>
    $(document).pjax(selector, [container], options) 
</script>
  • selector 给哪些 selector 绑定 pjax 事件,一般的为:"a", 如果要去掉一些外连的 URL, 这里的 selector 可以为:
    "a[href^='https://www.masterzc.cn']"。
  • [container] 内容变换容器,是指哪个容器里的内容发生的变换,如: '#pjax-content'。就是页面中只刷新的这个部分。
  • options 官方文档提供了更多的选项,以便更好地自定义选项。具体查考官方文档。以下列出我使用的一些选项。
    • container 替换的容器的 css 选择器。填你的替换容器 ID 即可。
    • timeout 超时就会被迫页面就会完全刷新,单位毫秒。
    • fragment 这个作为整个 pjax 框架,必须写上。

所以,代码可以这样写

<script>
    $(document).pjax('a[href^="<?php Helper::options()->siteUrl()?>"]:not(a[target="_blank"], a[no-pjax])', {
        container: '#pjax-container',
        fragment: '#pjax-container',
        timeout: 8000
    })
</script>

其他问题

pjax 采用的是异步请求资源,也就是每次请求数据不是重新获取整个页面的数据而是只会获取#pjax-container 容器里面的数据。所以如果一个函数在容器外面(如多说加载函数),在 A 页面没有,B 又需要的话,那么从 A 页面进入 B 页面,这个函数就不会执行。必须回调这个函数。

highlight

pjax 项目还提供了一些 pjax 事件。以便在 pjax 执行前后加载一些东西。

这里只需要使用 pjax:complete 这个事件

<script>
    $(document).pjax('a[href^="https://www.masterzc.cn/"]:not(a[target="_blank"], a[no-pjax])', {
    container: '#pjax-container',
    fragment: '#pjax-container',
    timeout: 8000
}).on('pjax:complete',function(event){
    $('pre code').each(function(i, block) {
        hljs.highlightBlock(block);
    });
})
</script>

####其他的js失效问题####
在**pjax:complete**事件 重载相关函数即可。
$(document).pjax('a[href^="https://www.masterzc.cn/"]:not(a[target="_blank"], a[no-pjax])', {
    container: '#pjax-container',
    fragment: '#pjax-container',
    timeout: 8000
}).on('pjax:complete',function(event){
    $('html').css('overflow','auto');
})

本文链接:https://www.masterzc.cn/archives/54.html
本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处

Title - Artist
0:00