Inline Style & Script Tags

How to add inner html to tags.

Introduction

The <style>, <script> and <noscript> tags are unique in that they can have inner content.

Inner Content

When working with the inner content of a tag, you can set the inner content using the textContent or innerHTML properties.

useHead({
  script: [
    {
      innerHTML: 'window.analytics = window.analytics || []',
    },
  ],
  style: [
    {
      textContent: 'body { background: salmon; color: cyan; }',
    },
  ]
})

Safely using innerHTML

Setting the inner content using textContent is the safest way if you are not sure about the content, however in some instances you will need to use innerHTML.

When using innerHTML the content will not be sanitised. Make sure you sanitise user input if providing it with this property.
const someUserScript = await loadMyUserScript()
useHead({
  script: [
    {
      // ❌ Eek! This is dangerous!
      innerHTML: someUserScript
    },
  ],
})

Shorthand Syntax

For ease of use, you can provide a string as the array entry and Unhead will choose the correct property to set.

useHead({
  script: [
    'window.analytics = window.analytics || []',
  ],
  style: [
    'body { background: salmon; color: cyan; }',
  ]
})
Did this page help you?