javascript - 如何使用 vanilla js 将包含样式标签的字符串按原样附加到文档头?

标签 javascript html css node.js reactjs

我正在使用 rapscallion 异步渲染模板服务器端在 Node 中。在渲染正文的时候,我有一个字符串(包含换行符)需要插入到文档头部:

// 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>

但它会导致数据属性丢失(我需要保留它,这样样式就不会在客户端重新呈现)。

最佳答案

使用 document.createElement('div')然后向其中插入字符串,从该片段中获取 DOM,以便将其插入到 <head> 中使用 appendChild :

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);

关于javascript - 如何使用 vanilla js 将包含样式标签的字符串按原样附加到文档头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43821883/

相关文章:

javascript - 切换 Google map 标记

html - 如何制作粘性侧边栏而不相互交叉

html - 删除 &lt;input type ="file"> 旁边的标签

html - css 中的框以方形着色而不是倾斜

javascript - 使用 Kendo UI 导出为 PDF(RTL 语言问题)

javascript - AngularJS ngIf 阻止在指令中查找元素

javascript - 如何删除 Node.JS 中的对象?

css - 如何为视差图像设置 100% 宽度?

html - 如何在加载网站上添加动线?

javascript - 溢出 :auto not working even with height set