捣鼓个人博客也有一段时间了,其间加了不少的插件,改来改去,最后打开也变得很慢了。问题主要有两个方面,一个是网络问题,因为托管在Github上,国内访问一直很慢,后来还是迁移到Coding上了,妥协了,给他加了个Hosted by Coding Pages。另一方面则是加载的问题,由于多了许多插件,导致网页加载变慢,特别是在添加live2d之后。所以打算做些工作优化一下博客。

外部链接优化

主要是告诉搜索引擎爬虫无需抓取目标页,同时告诉搜索引擎无需将的当前页的Pagerank传递到目标页。Google推荐是用nofollow,nofollow是HTML元标签(meta)的content属性和链接标签(a)的rel属性的一个值,告诉机器(爬虫)无需追踪目标页,为了对抗blogspam(博客垃圾留言信息)。但是如果是通过sitemap直接提交该页面,爬虫还是会爬取,这里的nofollow只是当前页对目标页的一种态度,并不代表其他页对目标页的态度。

主要作用
  • 防止不可信的内容,最常见的是博客上的垃圾留言与评论中为了获取外链的垃圾链接,为了防止页面指向一些拉圾页面和站点。
  • 付费链接:为了防止付费链接影响Google的搜索结果排名,Google建议使用nofollow属性。
  • 引导爬虫抓取有效的页面:避免爬虫抓取一些无意义的页面,影响爬虫抓取的效率。 其主要方法是给所有外部链接加上rel="external nofollow"属性,对外部链接target=”_blank”采用在新窗口种打开外部链接的方法。
安装
bash
npm install hexo-autonofollow --save
配置

编辑站点配置文件。

yaml
nofollow:
    enable: true
    exclude:
    - you domain

这里的exclude下主要填你的域名,为豁免域名。

在主页不显示某类文章

修改主题目录下layout的index.swig文件:

{% extends '_layout.swig' %}
{% import '_macro/post.swig' as post_template %}
{% import '_macro/sidebar.swig' as sidebar_template %}

{% block title %}{{ config.title }}{% if theme.index_with_subtitle and config.subtitle %} - {{config.subtitle }}{% endif %}{% endblock %}

{% block page_class %}
  {% if is_home() %} page-home {% endif %}
{% endblock %}

{% block content %}
  <section id="posts" class="posts-expand">
    {% for post in page.posts %}
	{% if post.categories!= 'Recommend' %}
      {{ post_template.render(post, true) }}
	{% endif %}
    {% endfor %}
  </section>

  {% include '_partials/pagination.swig' %}
{% endblock %}

{% block sidebar %}
  {{ sidebar_template.render(false) }}
{% endblock %}

在其中加入page的判断页面即可。

添加emoji支持😄

由于Hexo的默认Markdown语法不支持emoji表情,网上也有人替换了其Markdown渲染工具,但是又会引入新的Bug,所以就放弃了。后来看到有人照着Github的方式做了一个插件,在生成网页的时候将关键字替换成emoji的unicode字符,然后再利用JavaScript将字符替换成图片,这样即使图片加载失败还有字符fallback。其Repo在此

安装
bash
npm install hexo-filter-github-emojis --save
配置

编辑站点配置文件

yaml
vim _config.xml
githubEmojis:
  enable: true
  className: github-emoji
  unicode: false
  styles:
  localEmojis:

其中,localEmojis可以添加自己的本地表情。

Warning的处理

在安装完之后再执行hexo生成站点文件时,会有一个警告,主要内容如下:

DeprecationWarning: Calling an asynchronous function without callback is deprecated.

这个意思是调用无回调的异步函数的方法已经被废弃,可能是使用了writeFile函数。因此在其安装目录下寻找,后来在其index文件中找到了这个函数。修改方法如下:

bash
cd node_modules/hexo-filter-github-emojis
vim index.js

找到带有writeFile函数的一行,应该是这行:

fs.writeFile(path.join(__dirname, 'emojis.json'), JSON.stringify(githubEmojis, null, '\t'))

writeFile改为writeFileSync函数,即:

fs.writeFileSync(path.join(__dirname, 'emojis.json'), JSON.stringify(githubEmojis, null, '\t'))

之后再运行,警告消失。

后加

现在听说作者已经修复了这个问题,所以不需要改了。

静态资源压缩

网页加载速度优化,主要通过压缩网页的静态资源如JS,Html,CSS,图片等文件来达到加速效果。网上现在主要有两种,一种是直接用Hexo的插件,Hexo-Neat,还有一种是使用通用的压缩工具Gulp
这里主要使用Gulp。

安装

首先是安装Gulp插件:

bash
npm install gulp --save-dev

然后安装gulp相关插件:

bash
$ npm install gulp-clean-css --save-dev
$ npm install gulp-uglify --save-dev
$ npm install gulp-htmlmin --save-dev
$ npm install gulp-htmlclean --save-dev
$ npm install gulp-imagemin --save-dev
$ npm install del --save-dev
$ npm install run-sequence --save-dev
配置

添加一个gulpfile.js文件,在博客根目录下。

javascript
var gulp = require('gulp');
var minifycss = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var htmlmin = require('gulp-htmlmin');
var htmlclean = require('gulp-htmlclean');
var imagemin = require('gulp-imagemin');
var del = require('del');
var runSequence = require('run-sequence');
var Hexo = require('hexo');


gulp.task('clean', function() {
    return del(['public/**/*']);
});

// generate html with 'hexo generate'
var hexo = new Hexo(process.cwd(), {});
gulp.task('generate', function(cb) {
    hexo.init().then(function() {
        return hexo.call('generate', {
            watch: false
        });
    }).then(function() {
        return hexo.exit();
    }).then(function() {
        return cb()
    }).catch(function(err) {
        console.log(err);
        hexo.exit(err);
        return cb(err);
    })
})

gulp.task('minify-css', function() {
    return gulp.src(['./public/**/*.css','public/**/*.min.css'])
        .pipe(minifycss({
            compatibility: 'ie8'
        }))
        .pipe(gulp.dest('./public'));
});

gulp.task('minify-html', function() {
    return gulp.src('./public/**/*.html')
        .pipe(htmlclean())
        .pipe(htmlmin({
            removeComments: true,
            minifyJS: true,
            minifyCSS: true,
            minifyURLs: true,
        }))
        .pipe(gulp.dest('./public'))
});

gulp.task('minify-js', function() {
    return gulp.src(['./public/**/*.js','!public/**/*.min.js'])
        .pipe(uglify())
        .pipe(gulp.dest('./public'));
});

gulp.task('minify-img', function() {
    return gulp.src('./public/images/**/*.*')
        .pipe(imagemin())
        .pipe(gulp.dest('./public/images'))
})

gulp.task('minify-img-aggressive', function() {
    return gulp.src('./public/images/**/*.*')
        .pipe(imagemin(
        [imagemin.gifsicle({'optimizationLevel': 3}), 
        imagemin.jpegtran({'progressive': true}), 
        imagemin.optipng({'optimizationLevel': 7}), 
        imagemin.svgo()],
        {'verbose': true}))
        .pipe(gulp.dest('./public/images'))
})

gulp.task('compress', function(cb) {
    runSequence(['minify-html', 'minify-css', 'minify-img'], cb);
});

gulp.task('build', function(cb) {
    runSequence('clean', 'generate', 'compress', cb)
});

gulp.task('default', ['build'])

因为已经将hexo g生成站点文件的过程包含进去了,直接执行gulp即可。 但是不知道是不是Next版本更新的原因,导致js的压缩总是出问题,暂时先删掉了runSequence中的minify-js一项,之后再作讨论。

问题解决

原因找到了,是因为Gulp的uglify-js不支持ES6的语法,因此编译会出错。
解决方案:先使用babel编译。

  1. 安装
shell
npm install --save-dev gulp-babel babel-preset-es2015 babel-core
  1. 修改gulpfile.js文件 在变量定义中添加一行:
javascript
var babel = require("gulp-babel");

然后在.pipe(uglify())这一行前加一句:

.pipe(babel({presets: ['es2015']}))

问题解决。

替换谷歌字体库

众所周知,谷歌字体库访问通常情况都非常慢,于是决定使用国内的CND加速,但是之前360的字体库已经下架了,所以使用中科大的(虽然不下架应该也不会选择它 😄 )。 修改方式:
编辑主题的配置文件:

shell
vim theme/next/_config.xml

找到fonts的设置,在host:后面填写

//fonts.lug.ustc.edu.cn

host:中间注意保持空格。

后加

中科大字体库已经挂了,谷歌字体库也经常抽风。于是采用国内CDN加速,参考于Showfom大神的一篇博客

修改谷歌字体库

//fonts.googleapis.com修改为国内cdn加速的库,和上面一样,找到fonts的设置,在host:后面填写

//fonts.cat.net
替换CDNJS 开源 JS 库

只需要替换 cdnjs.cloudflare.comcdnjs.cat.net 即可。即:

vendors中的jquery: 后面添加自定义的地址:

https://ajax.cat.net/ajax/libs/jquery/3.2.1/jquery.min.js
修改Han字体的CDN

由于Han字体使用的CDN是cloudflare的,国内速度比较慢,因此替换其CDN:

han:后加:

https://cdnjs.cat.net/ajax/libs/Han/3.3.0/han.min.css
修改其他的CDN

最终修改后的配置文件内容如下:

yaml
# Script Vendors.
# Set a CDN address for the vendor you want to customize.
# For example
#    jquery: https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js
# Be aware that you should use the same version as internal ones to avoid potential problems.
# Please use the https protocol of CDN files when you enable https on your site.
vendors:
  # Internal path prefix. Please do not edit it.
  _internal: lib

  # Internal version: 2.1.3
  jquery: https://ajax.cat.net/ajax/libs/jquery/3.2.1/jquery.min.js

  # Internal version: 2.1.5
  # See: http://fancyapps.com/fancybox/
  fancybox: https://cdnjs.cat.net/ajax/libs/fancybox/3.1.25/jquery.fancybox.min.js
  fancybox_css: https://cdnjs.cat.net/ajax/libs/fancybox/3.1.25/jquery.fancybox.min.css

  # Internal version: 1.0.6
  # See: https://github.com/ftlabs/fastclick
  fastclick: https://cdnjs.cat.net/ajax/libs/fastclick/1.0.6/fastclick.min.js

  # Internal version: 1.9.7
  # See: https://github.com/tuupola/jquery_lazyload
  lazyload: https://cdnjs.cat.net/ajax/libs/lazyload/2.0.3/lazyload-min.js

  # Internal version: 1.2.1
  # See: http://VelocityJS.org
  velocity: https://cdnjs.cat.net/ajax/libs/velocity/1.5.0/velocity.min.js

  # Internal version: 1.2.1
  # See: http://VelocityJS.org
  velocity_ui: https://cdnjs.cat.net/ajax/libs/velocity/1.5.0/velocity.ui.min.js

  # Internal version: 0.7.9
  # See: https://faisalman.github.io/ua-parser-js/
  ua_parser: https://cdnjs.cat.net/ajax/libs/UAParser.js/0.7.9/ua-parser.min.js

  # Internal version: 4.6.2
  # See: http://fontawesome.io/
  fontawesome: https://cdnjs.cat.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css

  # Internal version: 1
  # https://www.algolia.com
  algolia_instant_js: 
  algolia_instant_css:

  # Internal version: 1.0.2
  # See: https://github.com/HubSpot/pace
  # Or use direct links below:
  # pace: //cdn.bootcss.com/pace/1.0.2/pace.min.js
  # pace_css: //cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-flash.min.css
  pace:
  pace_css:

  # Internal version: 1.0.0
  # https://github.com/hustcc/canvas-nest.js
  canvas_nest: https://cdnjs.cat.net/ajax/libs/canvas-nest.js/1.0.1/canvas-nest.min.js

  # three
  three:

  # three_waves
  # https://github.com/jjandxa/three_waves
  three_waves:

  # three_waves
  # https://github.com/jjandxa/canvas_lines
  canvas_lines:

  # three_waves
  # https://github.com/jjandxa/canvas_sphere
  canvas_sphere:

  # Internal version: 1.0.0
  # https://github.com/zproo/canvas-ribbon
  canvas_ribbon:

  # Internal version: 3.3.0
  # https://github.com/ethantw/Han
  han: https://cdnjs.cat.net/ajax/libs/Han/3.3.0/han.min.css

然后找出网页中所有其他的使用cloudflare加速的内容,替换掉。