Saturday 6 May 2017

How do I append a string containing a style tag as-is to the document head with vanilla js?

I'm asynchronously rendering a template serverside with rapscallion in node. At the point of rendering the body, I have a string (containing line breaks) that needs to be inserted in the document head:

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

Since at that point I've already sent the <head> to the client, I need to insert a script that sets these styles to the head clientside. But I'm having trouble getting this to work.

This approach works:

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

But it results in a loss of the data attribute (which I need to preserve so the styles won't get rerendered on the client).



via vsjn3290ckjnaoij2jikndckjb

No comments:

Post a Comment