-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloadCSS.ts
66 lines (58 loc) · 1.55 KB
/
loadCSS.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Options for {@link loadCSS} function
*/
interface LoadCSSOptions {
/**
* Media query for styles to apply
* @example 'print', 'all', 'screen and (max-width: 768px)' and etc.
*/
media?: string
/**
* Add custom attribute to the script tag
*
*/
attrs?: Record<string, string>
}
/**
* return type of {@link loadCSS} function
*/
interface LoadCSSReturn {
unload: () => void
linkTag: HTMLLinkElement
}
/**
* It loads a CSS file into the page
* @param {string} path - the path to the CSS file
* @param {LoadCSSOptions} [options] - {
* @returns An object with two properties:
* - unload: a function that removes the script tag
* - linkTag: the link tag that was created
* @linkcode https://github.com/GreatAuk/utopia-utils/blob/main/packages/dom/src/loadCSS.ts
*/
export function loadCSS(path: string, options?: LoadCSSOptions): LoadCSSReturn {
const {
attrs = {},
media,
} = options || {}
let linkEl = document.querySelector<HTMLLinkElement>(`link[href="${path}"]`)
if (!linkEl) {
linkEl = document.createElement('link')
linkEl.rel = 'stylesheet'
linkEl.href = path
if (media)
linkEl.media = media
Object.entries(attrs).forEach(([name, value]) => linkEl?.setAttribute(name, value))
document.head.appendChild(linkEl)
}
return {
/** remove the script tag */
unload: () => unload(path),
linkTag: linkEl,
}
}
/** remove the script tag */
function unload(path: string): void {
const linkEl = document.querySelector(`link[href="${path}"]`)
if (linkEl)
linkEl.remove()
}