Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ styleInject(css, options);
### insertAt

Type: `string`<br>
Possible values: `top`<br>
Possible values: `top`, `amp`<br>
Default: `undefined`

Insert `style` tag to specific position of `head` element.
Insert `style` tag to specific position of `head` element. If `amp` was selected, the whole CSS string gets injected in a single `<style amp-custom>...</style>` element, according to the [AMP docs](https://amp.dev/documentation/guides-and-tutorials/develop/style_and_layout/?format=websites#add-styles-to-a-page).

## License

Expand Down
42 changes: 28 additions & 14 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,37 @@
export default function styleInject(css, { insertAt } = {}) {
if (!css || typeof document === 'undefined') return

const ampStyleSelector = 'style[amp-custom]'

const head = document.head || document.getElementsByTagName('head')[0]
const style = document.createElement('style')
style.type = 'text/css'
const ampStyle = head.querySelector(ampStyleSelector) || style

if (insertAt === 'top') {
if (head.firstChild) {
head.insertBefore(style, head.firstChild)
} else {
head.appendChild(style)
}
} else {
head.appendChild(style)
}
switch (insertAt) {
// AMP only allows a single <script> tag with an 'amp-custom' attribute set
case 'amp':
style.setAttribute('amp-custom', '')
ampStyle.innerText += css

if (!head.querySelector(ampStyleSelector)) {
head.appendChild(ampStyle)
}
break
// By default styleInject appends a new <style> tag in <head>
case 'top':
default:
style.type = 'text/css'

if (style.styleSheet) {
style.styleSheet.cssText = css
} else {
style.appendChild(document.createTextNode(css))
}

if (style.styleSheet) {
style.styleSheet.cssText = css
} else {
style.appendChild(document.createTextNode(css))
if (head.firstChild && insertAt === 'top') {
head.insertBefore(style, head.firstChild)
} else {
head.appendChild(style)
}
}
}