Pjax全站支持语法高亮笔记

实现语法高亮

个人极力推荐Prism.JS,轻量级且支持语法很多,也很方便。

首先在官方download选择自己所需要的语法文件,下载prism.js和prism.css

打开主题的function.php插入下面的代码:


function add_prism() {
        wp_register_style(
            'prismCSS', 
            get_stylesheet_directory_uri() . '/prism.css' //自定义路径
         );
          wp_register_script(
            'prismJS',
            get_stylesheet_directory_uri() . '/prism.js'   //自定义路径
         );
        wp_enqueue_style('prismCSS');
        wp_enqueue_script('prismJS');
    }
add_action('wp_enqueue_scripts', 'add_prism');

就这样OK。在文章高亮代码编辑如下:


<pre class="language-php"><code class="language-php">  code_here </code></pre>

对无刷新 pjax的支持

解决方案

只需要在Ajax请求完成时执行highlightAll()函数,可在下面两种方法中选任意一种;

方法一:


// Rerun Prism syntax highlighting on the current page
Prism.highlightAll();

由于第一种方法Prism.js需要重新查找新增的DOM节点内容,资源占用相对要高,所以你也可以用第二种方法:

方法二:


// Say you have a code block like this
/**
      // This is some random code
      var foo = "bar"
**/ // Be sure to select the inner and not the // Using plain Javascript var block = document.getElementById('some-code') Prism.highlightElement(block); // Using JQuery Prism.highlightElement($('#some-code')[0]); 

像Pjax WordPress主题可以在footer添加:


<script data-no-instant>
    InstantClick.on('change', function(isInitialLoad) {
      if (isInitialLoad === false) {
          // support Prism
        if (typeof Prism !== 'undefined') Prism.highlightAll();
      }
    });
    InstantClick.init('mousedown');
</script>

转自https://iiong.com/pajx-website-syntax-highlighting.html