【发布时间】:2017-10-04 22:26:51
【问题描述】:
我在节点中使用rapscallion 异步渲染模板服务器端。在渲染正文时,我有一个字符串(包含换行符)需要插入到文档头部:
// this is what I have serverside
var stylestring = `<style type="text/css" data-style="some-id-that needs to be preserved">
.lfwARz {
margin-bottom: 0;
margin-top: 0;
}
</style>`
因为那时我已经将<head> 发送给客户端,我需要插入一个脚本来将这些样式设置到头部客户端。但我无法让它发挥作用。
这种方法有效:
// gets run clientside
<script>
var style = document.createElement('style')
style.type = 'text/css'
style.innerHTML = '${() => sheet.getStyleTags().replace(/(\r\n|\n|\r)/gm, '').replace(/<\/?style.*?>/g, '')}'
document.head.appendChild(style)
</script>
但这会导致 data 属性丢失(我需要保留它,这样样式就不会在客户端上重新呈现)。
【问题讨论】:
-
你是如何准确渲染模板的?
-
@Halcyon 我正在使用节点和rapscallion。我所做的基本上是这样的:github.com/FormidableLabs/rapscallion#example
-
你能做类似
document.head.appendChild(style_element)的事情吗? -
@Halcyon 不,因为它还不是有效的 dom 元素。我只有一个带有
'<style type="text/css">llfwARz { ...etc'的字符串。 -
@Halcyon 所以如果我这样做
document.head.appendChild(style_string)我会得到Uncaught SyntaxError: Unexpected token <
标签: javascript html css node.js reactjs