加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

Vue处事端渲染实践 ——Web应用首屏耗时最优化方案

发布时间:2019-03-22 03:33:36 所属栏目:建站 来源:counterxing
导读:跟着各大前端框架的降生和演变,SPA开始风行,单页面应用的上风在于可以不从头加载整个页面的环境下,通过ajax和处事器通讯,实现整个Web应用拒不更新,带来了极致的用户体验。然而,对付必要SEO、追求极致的首屏机能的应用,前端渲染的SPA是糟糕的。亏得V

产物情形下,打包后的客户端和处事端的Bundle会存储为vue-ssr-client-manifest.json与vue-ssr-server-bundle.json,通过文件流模块fs读取即可,但在开拓情形下,我建设了一个appSSR模块,在产生代码变动时,会触发Webpack热更新,appSSR对应的bundle也会更新,appSSR模块代码如下所示:

  1. let clientManifest;  
  2. let bundle;  
  3. const appSSR = {  
  4.   get bundle() {  
  5.     return bundle;  
  6.   },  
  7.   set bundle(val) {  
  8.     bundle = val;  
  9.   },  
  10.   get clientManifest() {  
  11.     return clientManifest;  
  12.   },  
  13.   set clientManifest(val) {  
  14.     clientManifest = val;  
  15.   }  
  16. };  
  17. module.exports = appSSR; 

通过引入appSSR模块,在开拓情形下,就可以拿到clientManifest和ssrBundle,项目标渲染中间件如下:

  1. const fs = require('fs');  
  2. const path = require('path');  
  3. const ejs = require('ejs');  
  4. const vue = require('vue');  
  5. const vssr = require('vue-server-renderer');  
  6. const createBundleRenderer = vssr.createBundleRenderer;  
  7. const dirname = process.cwd();  
  8. const env = process.env.RUN_ENVIRONMENT;  
  9. let bundle;  
  10. let clientManifest;  
  11. if (env === 'development') {  
  12.   // 开拓情形下,通过appSSR模块,拿到clientManifest和ssrBundle  
  13.   let appSSR = require('./../../core/app.ssr.js');  
  14.   bundle = appSSR.bundle;  
  15.   clientManifest = appSSR.clientManifest;  
  16. } else {  
  17.   bundle = JSON.parse(fs.readFileSync(path.resolve(__dirname, './dist/vue-ssr-server-bundle.json'), 'utf-8'));  
  18.   clientManifest = JSON.parse(fs.readFileSync(path.resolve(__dirname, './dist/vue-ssr-client-manifest.json'), 'utf-8'));  
  19. }  
  20. module.exports = async function(ctx) {  
  21.   ctx.status = 200;  
  22.   let html;  
  23.   let context = await ctx.getTplContext();  
  24.   ctx.logger('进入SSR,context为: ', JSON.stringify(context));  
  25.   const tpl = fs.readFileSync(path.resolve(__dirname, './newTemplate.html'), 'utf-8');  
  26.   const renderer = createBundleRenderer(bundle, {  
  27.     runInNewContext: false,  
  28.     template: tpl, // (可选)页面模板  
  29.     clientManifest: clientManifest // (可选)客户端构建 manifest  
  30.   });  
  31.   ctx.logger('createBundleRenderer  renderer:', JSON.stringify(renderer));  
  32.   try {  
  33.     html = await renderer.renderToString({  
  34.       ...context,  
  35.       url: context.CTX.url,  
  36.     });  
  37.   } catch(err) {  
  38.     ctx.logger('SSR renderToString 失败: ', JSON.stringify(err));  
  39.     console.error(err);  
  40.   }  
  41.   ctx.body = html;  
  42. }; 

怎样对现有项目举办改革?

根基目次改革

行使Webpack来处理赏罚处事器和客户端的应用措施,大部门源码可以行使通用方法编写,可以行使Webpack支持的全部成果。

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读