Node + Angular Universal SSR:渲染页面时如何设置设备宽度

时间:2018-03-22 07:24:50

标签: angular angular5 angular-universal

我正在寻找一种使用Angular Universal设置服务器端渲染的设备宽度的方法,因此我可以控制预渲染页面是移动还是桌面布局。

我正在使用核心ngExpressEngine进行渲染(与universal starter几乎相同。

session_start()

1 个答案:

答案 0 :(得分:0)

更新:如前所述,使用jsdom放弃了,因为它在渲染的页面上执行了脚本,这是不希望的。可能可以使用runScripts选项进行调整,但仍然会影响性能。用正则表达式替换呈现的字符串更快,更安全。下面的示例已更新以反映出来。


今天我遇到了同样的问题。已启用通用支持并启用@angular/flex-layout的Angular应用程序。

在浏览器上呈现此应用程序时,ObservableMedia中的@angular/flex-layout会正确报告媒体,例如:

// browser side MediaChange event
{
  matches: true,
  mediaQuery: "(min-width: 1280px) and (max-width: 1919px)",
  mqAlias: "lg",
  property: "",
  suffix: "Lg"
}

在服务器上呈现相同的应用程序时:

// server side MediaChange event
{
  matches: true,
  mediaQuery: "all",
  mqAlias: "",
  property: "",
  suffix: ""
}

因此,基本上,服务器端默认不知道客户端的媒体参数,这是可以理解的。

如果您有某种机制来传递客户端的设备宽度(例如,通过cookie,个性化API等),则可以使用 jsdom 正则表达式字符串替换 >修改渲染的文档。大致看起来像这样:

// DON'T USE JSDOM, BECAUSE IT WILL EXECUTE SCRIPTS WHICH IS NOT INTENDED
// this probably may cache generated htmls
// because they are limited by the number of media queries
/*
function updateMetaViewport(html: string, deviceWidth?: number): string {
  const dom = new JSDOM(html);
  const metaViewport = dom.window.document.head.querySelector<HTMLMetaElement>('meta[name="viewport"]');
  // if deviceWidth is not specified use default 'device-width'
  // needed for both default case, and relaxing rendered html
  metaViewport.content = `width=${deviceWidth ? deviceWidth : 'device-width'}, initial-scale=1`;
  return dom.serialize();     
}
*/

// INSTEAD REGEX WILL BE SIMPLIER AND FASTER FOR THIS TASK
// use regex string replace to update meta viewport tag
// can be optimized further by splitting html into two pieces
// and running regex replace over first part, and then concatenate
// replaced and remaining (if rendered html is large enough)
function updateMetaViewport(html: string, deviceWidth?: number, deviceHeight?: number): string {
  const width = `width=${deviceWidth ? deviceWidth : 'device-width'}`;
  const height = deviceHeight ? `, height=${deviceHeight}` : '';
  const content = `${width}${height}, initial-scale=1`;
  const replaced = html.replace(
    /<head>((?:.|\n|\r)+?)<meta name="viewport" content="(.*)">((?:.|\n|\r)+?)<\/head>/i,
    `<head>$1<meta name="viewport" content="${content}">$3</head>`
  );
  return replaced;
}

router.get('*', (req, res) => {

  // where it is provided from is out of scope of this question
  const userDeviceWidth = req.userDeviceWidth;
  const userDeviceHeight = req.userDeviceHeight;
  // then we need to set viewport width in html
  const document = updateMetaViewport(indexHtmlDocument, userDeviceWidth, userDeviceHeight);

  res.render('index.html', {
    bootstrap: AppServerModuleNgFactory,
    providers: [provideModuleMap(LAZY_MODULE_MAP)],
    url: req.url,
    document,
    req,
    res
  }, (err, html) => {
    if (err) {
      res.status(500).send(`Internal Server Error: ${err.name}: ${err.message}`);
    } else {
      // once rendered, we need to refine the view port to default
      // other wise viewport looses its responsiveness
      const relaxViewportDocument = updateMetaViewport(html);
      res.status(200).send(relaxViewportDocument);
    }
  });
});

然后以@angular/flex-layout表示的服务器端呈现将是:

{
  matches: true,
  mediaQuery: '(min-width: 600px) and (max-width: 959px)',
  mqAlias: 'sm',
  suffix: 'Sm',
  property: ''
}

这是正确且更有利的,因为响应组件的样式,布局将完全符合客户的期望。