最近yodu模板的用户要求我兼容typecho的Prismjs代码高亮插件,其实在《pjax(InstantClick) 常用的重载函数》中我就提到了Prismjs的pjax重载代码,但是经测试,还是有问题,于是今早又折腾了下,找到了方法。

插件方面改动

打开Prismjs代码高亮插件的Plugin.php文件

在第58行找到<script>var pres = document.getElementsByTagName('pre');改成<script data-no-instant>var pres = document.getElementsByTagName('pre');

在第64行找到<script src="' . $jsUrl . '"></script>改成<script src="' . $jsUrl . '" data-no-instant></script

在第66行找到<script defer="defer" src="' . Helper::options()->pluginUrl . '/Prismjs/line-number-wrap-fix.js' . '"></script>改成<script defer="defer" src="' . Helper::options()->pluginUrl . '/Prismjs/line-number-wrap-fix.js' . '" data-no-instant></script>

就是挨个加data-no-instant

instantclick模板方面调整

在重载函数里添加

 if (typeof Prism !== 'undefined') {
Prism.highlightAll(true,null);}

这样,代码高亮就完全好使了

但是随后又发现行号会不显示,于是想在重载下行号的函数,整理下就是如下代码

 if (typeof Prism !== 'undefined') {<?php  if (Helper::options()->plugin('Prismjs')->showln): ?>
var pres = document.getElementsByTagName('pre');
                for (var i = 0; i < pres.length; i++){
                    if (pres[i].getElementsByTagName('code').length > 0)
                        pres[i].className  = 'line-numbers';}<?php endif; ?>
Prism.highlightAll(true,null);
}

php部分判断插件是否使用了显示行号,使用就重载行号函数;
因为是对插件进行了判断,所以如果没启用插件,直接用上面代码会导致网站错误500。

版权属于:泽泽社长
本文链接:https://blog.zezeshe.com/archives/instantclick-compatible-prismjs-plugin.html
本站未注明转载的文章均为原创,并采用 CC BY-NC-SA 4.0 授权协议,转载请注明来源,谢谢!