【问题标题】:How do I append a string containing a style tag as-is to the document head with vanilla js?如何使用 vanilla js 将包含样式标签的字符串按原样附加到文档头?
【发布时间】: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>`

因为那时我已经将&lt;head&gt; 发送给客户端,我需要插入一个脚本来将这些样式设置到头部客户端。但我无法让它发挥作用。

这种方法有效:

// 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 元素。我只有一个带有'&lt;style type="text/css"&gt;llfwARz { ...etc' 的字符串。
  • @Halcyon 所以如果我这样做document.head.appendChild(style_string) 我会得到Uncaught SyntaxError: Unexpected token &lt;

标签: javascript html css node.js reactjs


【解决方案1】:

使用document.createElement('div'),然后将字符串插入其中,从该片段中获取DOM,以便可以使用appendChild将其插入&lt;head&gt;

var fragment = document.createElement('div');
// remove newlines from the string and insert it in the fragment
fragment.innerHTML = the_style_string.replace(/(\r\n|\n|\r)/gm, '');
document.head.appendChild(fragment.firstChild);

【讨论】:

  • 感谢您的回答,但字符串已经包含样式标签。所以这行不通。如果可能的话,我宁愿直接将其解析为一个元素。
  • 试试这个:document.head.innerHTML = document.head.innerHTML + '&lt;style type="text/css"&gt; body{background: red}&lt;style&gt;'
  • @vsjn3290ckjnaoij2jikndckjb 更新了答案。
  • 我已经测试了你的答案。它失败了:Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
  • 然后,我只需在&lt;head&gt; 部分中设置一个硬编码的&lt;style&gt; 标记,并通过其ID 更新其内部HTML:document.getElementById('dynamic-style').innerHTML=the_style_string.replace(/&lt;\/?style.*?&gt;/g, "");。这是最简单的选择。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-09
  • 2021-12-11
  • 1970-01-01
相关资源
最近更新 更多