menu 刘兴刚博客
more_vert
chevron_right 首页 » WEB开发 » 正文
hexo博客进阶-性能优化
2016-12-06 | WEB开发 | 暂无评论 | 7005 次阅读 | 1109字

采用Hexo框架搭建了本博客,使用了Next主题,基于Node.js和Git,最大的感觉是解析文章很快,网页很简介大方,符合个人博客当初的设想。但是hexo自动生成的html代码中有许多的空白,以前看过google的源码密密麻麻的一大片可以说没有任何空格,当时是非常的羡慕google的技术,没曾想自己的博客也可以如此,那就是用gulp自动化工具压缩,网上看了需要相关文章,本地测试一直有问题,拿来主义让自己太过于懒散,今天认认真真的根据自身博客的文件目录情况修改了一下gulpfile.js,非常顺利的压缩了本站。

安装依赖

建议安装淘宝的cnpm提速。

(c)npm install gulp gulp-uglify gulp-minify-css gulp-htmlmin gulp-htmlclean gulp-imagemin gulp-concat –-save-dev

推荐安装 cnpm,npm服务器在国外,网络影响大,甚至还会遇到需要翻墙才能下载插件的情况,因此推荐安装cnpm。cnpm跟npm用法完全一致,只是在执行命令时将npm改为cnpm

创建gulpfile.js

在hexo blog文件夹下创建gulpfile.js:

var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    cssmin = require('gulp-minify-css'),
    imagemin = require('gulp-imagemin'),
    htmlmin = require('gulp-htmlmin'),
    htmlclean = require('gulp-htmlclean');
    concat = require('gulp-concat');
//JS压缩
gulp.task('uglify', function() {
    return gulp.src(['./public/js/**/.js','!./public/js/**/*min.js'])//只是排除min.js文件还是不严谨,一般不会有问题,根据自己博客的修改我的修改为return gulp.src(['./public/**/*.js','!./public/zuoxi/**/*.js',,'!./public/radio/**/*.js'])
        .pipe(uglify())
        .pipe(gulp.dest('./public/js'));//对应修改为./public即可
});
//public-fancybox-js压缩
gulp.task('fancybox:js', function() {
    return gulp.src('./public/vendors/fancybox/source/jquery.fancybox.js')
        .pipe(uglify())
        .pipe(gulp.dest('./public/vendors/fancybox/source/'));
});
// 合并 JS
gulp.task('jsall', function () {
    return gulp.src('./public/**/*.js')
    // 压缩后重命名
        .pipe(concat('app.js'))
        .pipe(gulp.dest('./public'));
});
//public-fancybox-css压缩
gulp.task('fancybox:css', function() {
    return gulp.src('./public/vendors/fancybox/source/jquery.fancybox.css')
        .pipe(cssmin())
        .pipe(gulp.dest('./public/vendors/fancybox/source/'));
});
//CSS压缩
gulp.task('cssmin', function() {
    return gulp.src(['./public/css/main.css','!./public/css/*min.css'])   
        .pipe(cssmin())
        .pipe(gulp.dest('./public/css/'));
});
//图片压缩
gulp.task('images', function() {
    gulp.src('./public/uploads/*.*')
        .pipe(imagemin({
            progressive: false
        }))
        .pipe(gulp.dest('./public/uploads/'));
});
// 压缩 public 目录 html文件 public/**/*.hmtl 表示public下所有文件夹中html,包括当前目录
    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('build', ['uglify', 'jsall', 'cssmin', 'images', 'fancybox:js', 'fancybox:css','minify-html']);

刚开始光想图省事,直接复制网上的提示无法压缩javascript,像带.min.js这样的js无须再压缩,可能再次压缩就会提示错误吧,所以像我们这种小白用户还是按部就班的根据自己网站目录设置压缩路径。

还是对错误耿耿于怀,对比了一下,逐一排查最终找到根源,提示错误如下:

events.js:160
      throw er; // Unhandled 'error' event
      ^
GulpUglifyError: unable to minify JavaScript
    at createError (d:\hexo\node_modules\.2.0.0@gulp-uglify\lib\c
reate-error.js:6:14)
    at wrapper (d:\hexo\node_modules\.4.17.2@lodash\_createHybrid
.js:87:15)
    at trycatch (d:\hexo\node_modules\.2.0.0@gulp-uglify\minifier
.js:26:12)
    at DestroyableTransform.minify [as _transform] (d:\hexo\node_
modules\.2.0.0@gulp-uglify\minifier.js:76:19)
    at DestroyableTransform.Transform._read (d:\hexo\node_modules
\.2.2.2@readable-stream\lib\_stream_transform.js:159:10)
    at DestroyableTransform.Transform._write (d:\hexo\node_module
s\.2.2.2@readable-stream\lib\_stream_transform.js:147:83)
    at doWrite (d:\hexo\node_modules\.2.2.2@readable-stream\lib\_
stream_writable.js:347:64)
    at writeOrBuffer (d:\hexo\node_modules\.2.2.2@readable-stream
\lib\_stream_writable.js:336:5)
    at DestroyableTransform.Writable.write (d:\hexo\node_modules\
.2.2.2@readable-stream\lib\_stream_writable.js:274:11)
    at write (d:\hexo\node_modules\vinyl-fs\node_modules\readable
-stream\lib\_stream_readable.js:623:24)

原因是一些已经压缩过的js文件再次压缩就提示这个错误,故对gulpfile.js加入已经压缩文件的排除;

执行优化命令

清空hexo public文件夹

hexo clean
hexo g
gulp build
hexo d

连续执行4个命令太麻烦, 可以直接在根目录下的package.json文件中生成写入scripts:

"scripts": {
  "build": "hexo clean && hexo g && gulp build && hexo deploy"
  }

然后直接执行如下命令就可以了

npm run build

原先都是hexo clean && hexo generate --deploy来自动更新博文,虽然命令不长,还是不如上面一条简单命令geek,至此,可以得到一个html、css、js、image都更优化的/public文件夹,最后再用各种评测工具测试一下你的博客打开速度吧!~

把谷歌字体库替换为国内的库

注意,由于360公共前端库已经停止服务,所以本教程作废。另外经过测试发现Google字体库的中国
区服务器位于北京和上海,访问速度非常快,已经没必要再换其他字体库了。

由于谷歌字体库偶尔加载非常慢,可以将其替换,这里采用360CDN服务。以Next主题为例,可以找到your-hexo-sitethemesnextlayout_partialsheadexternal-fonts.swig中有这段语句:

{% set font_families += '&subset=latin,latin-ext' %}
{% set font_host = font.host | default('//fonts.googleapis.com') %}
<link href="{{ font_host }}/css?family={{ font_families }}" rel="stylesheet" type="text/css">

只需要将//fonts.googleapis.com改为//fonts.useso.com,即可将默认加载的谷歌字体库换成360的。

把多说评论依赖的embed.js放至底部

考虑到网站性能优化,大部分情况下建议把JavaScript放在底部,这样页面既可以逐步呈现,也可以提高下载的并行度。仍以Next主题为例,将your-hexo-sitethemesnextlayout_scriptsthird-partycommentsduoshuo.swig中的

(document.getElementsByTagName('head')[0]

修改为

(document.getElementById('footer')

即可。

尝试一下InstantClick 黑科技

非常羡慕大师级JerryQu的博客,打开可以说跟不刷新页面的ajax效果太酷了,由于自身没那个技术,只能用不是特别优雅的黑科技了。InstantClick 的思路非常巧妙,它利用鼠标点击链接前的短暂时间(统计说是平均400ms)进行预加载,从而在感观上实现了迅速打开页面的效果。当你在打开页面的时候,其实页面已经加载到本地了,也就会很快能个完成渲染。

InstantClick 并不能滥用,许多js无法与它兼容,比如 谷歌分析,百度统计,另外还有fancybox 。

初始化,以及解决部分js无法加载的问题:

 <script src="/js/instantclick.min.js" data-no-instant></script>
    <script data-no-instant>
    InstantClick.on('change', function(isInitialLoad) {
      if (isInitialLoad === false) {
        if (typeof MathJax !== 'undefined') // support MathJax
          MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
        if (typeof prettyPrint !== 'undefined') // support google code prettify
          prettyPrint();
        if (typeof _hmt !== 'undefined')  // support 百度统计
          _hmt.push(['_trackPageview', location.pathname + location.search]);
        if (typeof ga !== 'undefined')  // support google analytics
            ga('send', 'pageview', location.pathname + location.search);
      }
    });
    InstantClick.init();
    </script>

这时候对于所有链接都开启 预加载模式,但是可以针对部分链接假如黑名单:

<a href="/blog/" data-no-instant>Blog</a>

针对自己博客就是修改/themes/next/layout/_partials/head.swig,在这个文件底部加上上面的对instantclick.min.js引入即可,然后把instantclick.min.js文件放到/themes/next/source/js/下即可。也许是做了html压缩,同时也做了360的cdn加速,引入instantclick后没有感觉网站快多少。

发表评论
暂无评论
textsms
account_circle
email
link
arrow_forward 下一篇
""