Crayon Syntax Highlighter加载优化

Home / Article MrLee 2015-5-13 2816

做技术博客的朋友一般都会用到代码高亮,本站用的是Crayon Syntax Highlighter,这个插件非常之强大,支持的语言也非常之多,所以功能越强大自身代码和样式也是很大的,文件大了就影响网站的打开速度影响用户体验。那么我们是不是只需要让它在文章页面显示就行了呢?首页和其它页面是不需要代码高亮的。自然也不用加载对应的JS和CSS样式了。 打开博客目录并转到wp-content\plugins\crayon-syntax-highlighter目录中,打开crayon_wp.class.php
大约在871行的 public static function wp_head()函数中第一行添加下面两句代码
public static function wp_head() {
CrayonLog::debug('head');
if(!is_single())
return;//不是内容页面直接返回
self::$wp_head = TRUE;
if (!self::$enqueued) {
CrayonLog::debug('head: missed enqueue');
// We have missed our chance to check before enqueuing. Use setting to either load always or only in the_post
CrayonSettingsWP::load_settings(TRUE); // Ensure settings are loaded
// If we need the tag editor loaded at all times, we must enqueue at all times
if (!CrayonGlobalSettings::val(CrayonSettings::EFFICIENT_ENQUEUE) || CrayonGlobalSettings::val(CrayonSettings::TAG_EDITOR_FRONT)) {
CrayonLog::debug('head: force enqueue');
// Efficient enqueuing disabled, always load despite enqueuing or not in the_post
self::enqueue_resources();
}
}
// Enqueue Theme CSS
if (CrayonGlobalSettings::val(CrayonSettings::ENQUEUE_THEMES)) {
self::crayon_theme_css();
}
// Enqueue Font CSS
if (CrayonGlobalSettings::val(CrayonSettings::ENQUEUE_FONTS)) {
self::crayon_font_css();
}
}
现在不是文章内容页是不会加载代码高亮的JS和CSS样式的,但是内容还是会被替换,我们还要处理下一步的工作。继续看代码,大约在451行的 public static function the_posts($posts)函数,添加一个判断语句is_single,修改后部分代码:
    /* Search for Crayons in posts and queue them for creation */
    public static function the_posts($posts) {
        CrayonLog::debug('the_posts');
		if(!is_single())
			return $posts;//不是内容页面直接返回
        // Whether to enqueue syles/scripts
        CrayonSettingsWP::load_settings(TRUE); // We will eventually need more than the settings
本来修改是很简单的,在is_admin后面加一个语句||!is_single()就行了,但是发现在
if (defined('ABSPATH')) {
if (!is_admin()) {
使用is_single并没有任何效果,估计是这个时候还没初始的原因,值是NULL。因对WP不熟,所以只能在里面添加single判断,发现是有效的!所以暂时用这种方法解决。

本文链接:https://www.it72.com/2871.htm

推荐阅读
最新回复 (0)
返回