我的网站开发技术经验总结 我的网站开发技术经验总结
首页

fangdown

我的网站开发技术经验总结
首页
  • 认识ESM
  • chrome-talend插件,类似postman
  • sequelize 使用及技巧
  • UML工具Power Designer建表
  • sequelize相关操作文档
  • 解决抖音获取签名及并发的问题
  • 记一次解决抖音分享页混淆字体,字体图标转UID解决方案
  • 获取抖音用户作品列表信息
  • 获取抖音用户作品列表信息-进阶
  • 获取抖音用户作品列表信息-进阶3
  • 如何根据抖音号获取用户信息
  • 获取用户最新视频
  • 模块化-import和require的区别
  • eslint规范
  • js容错处理
  • js-数组分组,执行promise
  • reduce使用遇到的问题
  • 正则匹配html的元素内容
  • taro 小程序 弹窗层禁止底部滚动
  • 公众号签名问题
  • CentOS7中MariaDB重置密码
  • nginx多域名配置
  • node访问接口,得到乱码的结果,原因-Accept-Encoding
  • node写文件到json中
  • node抓取html内容
  • Node.js使用ES6语法
  • express 使用cors中间件解决跨域
  • node + express + session + redis 进行持久化缓存
  • node中读取文件夹,获取文件名称
  • pm2常用命令
  • 使用pm2管理后台node服务
  • typescript puppeteer支持window及document属性
  • node读取json文件
  • node中使用redis缓存
  • node + github的webhook完成自动部署
  • vuepress-blog的性能优化-CDN
    • 概况
    • 问题
    • 优化
      • 个人站点
      • 优化策略
      • 自定义前缀
      • 资源上传到COS
    • 总结
  • CENTOS7下安装REDIS
  • promise then和catch的学习和使用
  • promise在循环中的串行并行用法
  • puppeteer常用知识
  • centos部署安装puppeteer
  • python的学习和使用
  • Taro+TypeScript - Mobx实践
  • 爬虫系列 --- 反爬机制和破解方法汇总
  • 安全-html转码
  • taro中使用animation动画
  • charles 使用
  • Mac下VSCode设置iTerm2终端样式
  • centos一步步完成站点部署
  • 云闪付做地铁的思路
  • 准备技能
  • 备案pc项目介绍
  • 备案小程序项目介绍
  • 小程序二维码扫码功能
  • 小程序域名组件开发
  • 小程序添加水印
  • 规则引擎优化
  • 记一次hooks代替redux的经历
  • 通过nodejs+koa+stream进行服务端图片代理
  • nodeJs接入log4j日志
  • nodejs+typescript项目中添加全局global属性
  • create-react-app 安装 bizcharts 项目崩溃
  • 使用MutationObserver监控dom的变化
  • 服务器重启后启动相关服务
  • moment国际化的问题
  • 项目经验
fangdown
2019-11-25
目录

vuepress-blog的性能优化-CDN

提示

博客网站性能优化之旅

# 概况

  1. 使用vuepress构建的博客
  2. 使用了vuepress-theme-repo的主题

# 问题

网站打开的速度比较慢,使用chrome加载资源瀑布流分析, 图片、js资源加载速度太慢了, 不是很大,几十k,最大的js,170k,但是加载时间却要5s、10s的,受不了!!!急需优化。

# 优化

# 个人站点

之前购买腾讯云的服务器, 配置较低

# 优化策略

  1. 构建时自定义加上cdn前缀
  2. 将静态资源如js/css/image 等部署到腾讯云存储COS上

# 自定义前缀

publicPath配置,设置好前缀后,build出来的资源路径会加上这个cdn地址

// .vuepress/config.js
"title": "知识分享",
"configureWebpack": {
    output:{
      publicPath: 'https://cdn.git123.cn/vblog/'
    }
  },

# 资源上传到COS

  • 打包输出目录 html
  • 将html中的资源有选择的存储到腾讯云COS上

'use strict';
/** *
 * 腾讯云存储-文件夹上传
*/
const fs = require('fs'); // node的文件插件
const ora = require('ora'); // 日志打印归于一行插件
const chalk = require('chalk'); // 日志美化插件
const COS = require('cos-nodejs-sdk-v5'); // 腾讯cos插件
const glob = require('glob'); // 遍历文件夹插件
const config = require('./tx-cos-config'); // 配置文件
const FILES_PATH = 'html/**/*.*'; // 打包后静态资源路径
const IGNORE_PATH = '*/index.html';  // 忽略index.html文件

/**
 * 发送文件至cos类
 * @class DeployCos
 */
class DeployCos {
  constructor() {
    this.filesPath = FILES_PATH; // 打包后的静态资源路径
    this.cos = this._createCosInstance();
    this.spinner = this._createSpinner();
    this.total = 0; // 总文件数

    this.main();
  }

  /**
   * 获取文件路径,并上传至cos
   * @memberof DeployCos
   */
  main() {
    glob(
      this.filesPath,
      {
        ignore: [IGNORE_PATH]
      },
      (err, fileNames) => {
        this.total = fileNames.length;

        let promiseArr = fileNames.map((file, index) => {
          return this._uploadFile(file, index + 1); // 因为index从零开始,所以这里加一
        });

        Promise.all(promiseArr)
          .then(res => {
            this.spinner.succeed(); // 结束上传进度条打印
            console.log(
              chalk.cyan('\n  Send files to tencent cos success.\n')
            );
          })
          .catch(err => {
            console.log(
              chalk.red('  Send failed with errors.\n', err)
            );
            console.log('err', err)
          });
      }
    );
  }

  /**
   * 创建cos实例
   */
  _createCosInstance() {
    return new COS({
      SecretId: config.SecretId,
      SecretKey: config.SecretKey
    });
  }

  /**
   * 创建进度条
   */
  _createSpinner() {
    return ora({
      text: this._getTip(0, 0),
      color: 'green'
    }).start();
  }

  /**
   * 展示进度提示条
   * @param {number} index 当前文件索引
   * @param {number} sum 总文件数
   * @memberof DeployCos
   */
  _getTip(index, sum) {
    let percentage = sum === 0 ? 0 : Math.round((index / sum) * 100);
    return `Uploading to Tencent COS: ${
      percentage === 0 ? '' : percentage + '% '
      }${index}/${sum} files uploaded`;
  }

  /**
   * 实际调用cos接口上传文件函数
   * @param {String} file 文件相对路径
   * @param {number} index 文件计数器
   * @memberof DeployCos
   */
  _uploadFile(file, index) {
    return new Promise((resolve, reject) => {
      /**
       * 因为不希望cos上的路径多一层dist,所以这里移除
       * - 不移除,形如: [cos路径]/[dist/static/xx]
       * - 移除后,形如: [cos路径]/[static/xx]
       */
      let removeDistFilePath = file.replace('html/', '');
      /** 上传文件基础配置 */
      let baseConfig = {
        Bucket: config.Bucket, // 存储桶 格式:test-1250000000
        Region: config.Region, // 地域
        Key: `vblog/${removeDistFilePath}` // [cos存储路径]/[文件相对存储路径]
      };
      // 根据文件大小判断使用何种方式上传,大于1M的使用分块上传
      if (fs.statSync(file).size > 1024 * 1024) {
        this.cos.sliceUploadFile(
          {
            ...baseConfig,
            FilePath: file
          },
          (err, data) => {
            this.spinner.text = this._getTip(index, this.total);
            return err ? reject(err) : resolve(data);
          }
        );
      } else {
        // 这个有问题
        // this.cos.putObject(
        //   {
        //     ...baseConfig,
        //     Body: fs.createReadStream(file),
        //     ContentLength: fs.statSync(file).size // putObject接口必须传文件大小
        //   },
        //   (err, data) => {
        //     this.spinner.text = this._getTip(index, this.total);
        //     return err ? reject(err) : resolve(data);
        //   }
        // );
        this.cos.sliceUploadFile(
          {
            ...baseConfig,
            FilePath: file
          },
          (err, data) => {
            this.spinner.text = this._getTip(index, this.total);
            return err ? reject(err) : resolve(data);
          }
        );
      }
    });
  }
}

new DeployCos();  // 执行推送

# 总结

  • 本次优化的思路: 静态资源上传到cdn上,减少网络传输时间
  • 本次优化的难点:1, 资源上传到cdn,上传方法;2. vuepress改写webpack配置
#性能优化
上次更新: 2021/12/19, 18:05:42
node + github的webhook完成自动部署
CENTOS7下安装REDIS

← node + github的webhook完成自动部署 CENTOS7下安装REDIS→

最近更新
01
多分支修复撞车的问题
05-01
02
如何成为架构师
01-23
03
服务器部署全过程
11-23
更多文章>
Theme by Vdoing | Copyright © 2019-2026 fangdown | 粤ICP备19079809号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式