-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.browser.js
57 lines (37 loc) · 1.09 KB
/
index.browser.js
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
function jsincss(
stylesheet = event => '',
selector = window,
events = ['load', 'resize', 'input', 'click', 'reprocess']
) {
function registerEvent(target, event, id, stylesheet) {
return target.addEventListener(
event,
e => populateStylesheet(id, stylesheet, e)
)
}
function populateStylesheet(id, stylesheet, e) {
let tag = document.querySelector(`#jsincss-${id}`)
if (!tag) {
tag = document.createElement('style')
tag.id = `jsincss-${id}`
document.head.appendChild(tag)
}
const currentStyles = tag.textContent
const generatedStyles = stylesheet(e)
if (!currentStyles || (generatedStyles !== currentStyles)) {
return tag.textContent = generatedStyles
}
}
let id = Date.now() + Math.floor(Math.random() * 100)
if (selector === window) {
return events.forEach(event =>
registerEvent(window, event, id, stylesheet)
)
} else {
return document.querySelectorAll(selector).forEach(tag =>
events.forEach(event =>
registerEvent(tag, event, id, stylesheet)
)
)
}
}