5

【单页面应用 】发版后如何【通知用户端更新】

 3 years ago
source link: https://segmentfault.com/a/1190000039968885
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【单页面应用 】发版后如何【通知用户端更新】

【单页面 】发版后如何【通知用户端更新】
现象描述:

首先技术栈,是vue全家桶技术栈。典型spa单页应用,每次有新功能的上线,都需要主动通知,使用者自主刷新页面【强刷】,才能出现新功能。

产生原因:
每次打包发版【代码有变化】,index.html,网站即入口文件是变化的。
但是在单页面应用,页面跳转,都在同一个浏览器线程中,不会再一次请求index.html 资源,即使你对 index.html 资源不缓存策略,即设置响应头部信息为cache-control: no-store 也是不好使。用户还得必须刷新。

那么解决策略如何,一图胜千言:

  1. 介绍 webpack【4版本】 中 插件如何实现
// 获取并注入版本号 未写点【这里还可以写 把版本号 和 项目 名 发送到服务器,作版本记录】
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = class WebpackVersionPlugin {
  constructor(options = { }) {
    this.options = Object.assign({
      versionName: '$AppVersion'
    }, options)
  }
  apply(complier) {
    const { versionName } = this.options;
    complier.hooks.emit.tapAsync('WebpackVersionPlugin', (compilation, callback) => {
      const { hash } = compilation
// 需要在 index.html 注入变量 【在htmlWebpackPlugin 钩子里处理 详细看官方文档】     HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
        'MyPlugin', 
        (data, cb) => {
          const htmlScriptStr = `<script>window.${versionName}="${hash}"</script>`
          // 插入到第一个 script标签前面
          data.html = data.html.replace(/(<script)/,  `${htmlScriptStr}$1`)
          cb(null, data)
        }
      )
      callback()
    })
  }
}

效果如下:

2 为什么用 location.reoload, 通过轮训hash版本比较,可以通知 用户是否 刷新页面【ui层面】,是则调用reload,否则不操作


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK