Adrià Vilanova Martínez | d7951b2 | 2024-05-25 22:13:32 +0200 | [diff] [blame] | 1 | export interface StylesheetAttributes { |
| 2 | media?: string; |
| 3 | } |
| 4 | |
| 5 | export function injectStylesheet( |
| 6 | stylesheetName: string, |
| 7 | attributes: StylesheetAttributes = {}, |
| 8 | ) { |
Adrià Vilanova Martínez | e7f9be8 | 2024-05-31 22:37:04 +0200 | [diff] [blame] | 9 | const link = document.createElement('link'); |
Adrià Vilanova Martínez | d7951b2 | 2024-05-25 22:13:32 +0200 | [diff] [blame] | 10 | link.setAttribute('rel', 'stylesheet'); |
| 11 | link.setAttribute('href', stylesheetName); |
| 12 | if ('media' in attributes) { |
| 13 | link.setAttribute('media', attributes['media']); |
| 14 | } |
| 15 | document.head.appendChild(link); |
| 16 | return link; |
| 17 | } |
| 18 | |
| 19 | export function injectStyles(css: string) { |
| 20 | injectStylesheet('data:text/css;charset=UTF-8,' + encodeURIComponent(css)); |
| 21 | } |
| 22 | |
| 23 | export function injectScript(scriptName: string, prepend = false) { |
Adrià Vilanova Martínez | e7f9be8 | 2024-05-31 22:37:04 +0200 | [diff] [blame] | 24 | const script = document.createElement('script'); |
Adrià Vilanova Martínez | d7951b2 | 2024-05-25 22:13:32 +0200 | [diff] [blame] | 25 | script.src = scriptName; |
| 26 | const root = document.head || document.documentElement; |
| 27 | if (prepend) { |
| 28 | root.prepend(script); |
| 29 | } else { |
| 30 | root.append(script); |
| 31 | } |
| 32 | } |