Skip to content
This repository has been archived by the owner on Nov 9, 2024. It is now read-only.

Commit

Permalink
Fix: place style tag before first style,link tag
Browse files Browse the repository at this point in the history
  • Loading branch information
atomiks committed Aug 1, 2019
1 parent 19b8383 commit 20f9c29
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 10 deletions.
6 changes: 3 additions & 3 deletions src/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
30 changes: 23 additions & 7 deletions test/spec/css.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})

0 comments on commit 20f9c29

Please sign in to comment.