diff --git a/src/css.ts b/src/css.ts index c0ba865ea..a01bb9db5 100644 --- a/src/css.ts +++ b/src/css.ts @@ -10,10 +10,10 @@ export function injectCSS(css: string): void { style.textContent = css style.setAttribute('data-__NAMESPACE_PREFIX__-stylesheet', '') const head = document.head - const { firstChild } = head + const firstStyleOrLinkTag = head.querySelector('style,link') - if (firstChild) { - head.insertBefore(style, firstChild) + if (firstStyleOrLinkTag) { + head.insertBefore(style, firstStyleOrLinkTag) } else { head.appendChild(style) } diff --git a/test/spec/css.test.js b/test/spec/css.test.js index 5c05ddbc9..782d45bab 100644 --- a/test/spec/css.test.js +++ b/test/spec/css.test.js @@ -10,16 +10,32 @@ describe('injectCSS', () => { it('injects a string of css styles into the document `head`', () => { expect(document.head.querySelector('style')).toBe(null) injectCSS(styles) - const styleNode = document.head.querySelector('style') - expect(styleNode).toBeTruthy() - expect(styleNode.textContent).toBe(styles) - styleNode.remove() + const stylesheet = document.head.querySelector( + '[data-__NAMESPACE_PREFIX__-stylesheet]', + ) + expect(stylesheet).not.toBe(null) + expect(stylesheet.textContent).toBe(styles) }) - it('places the node before the first child if it exists', () => { + it('places the node before the first style or link node (link before style)', () => { document.head.append(document.createElement('title')) + document.head.append(document.createElement('link')) + document.head.append(document.createElement('style')) injectCSS(styles) - const styleNode = document.head.querySelector('style') - expect(document.head.children[0]).toBe(styleNode) + const stylesheet = document.head.querySelector( + '[data-__NAMESPACE_PREFIX__-stylesheet]', + ) + expect(document.head.children[1]).toBe(stylesheet) + }) + + it('places the node before the first style or link node (link after style)', () => { + document.head.append(document.createElement('title')) + document.head.append(document.createElement('style')) + document.head.append(document.createElement('link')) + injectCSS(styles) + const stylesheet = document.head.querySelector( + '[data-__NAMESPACE_PREFIX__-stylesheet]', + ) + expect(document.head.children[1]).toBe(stylesheet) }) })