如何将一个包含样式标签的string作为原始文件添加到文件头中?
我asynchronous呈现在rapscallion模板serverside节点中。 在渲染主体的时候,我需要在文档头中插入一个string(包含换行符):
// 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')
然后插入string,从该片段获取DOM,以便使用appendChild
将其插入<head>
:
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);