我正在使用 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/