This repository has been archived by the owner on May 5, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
preact-script2.js
102 lines (86 loc) · 2.24 KB
/
preact-script2.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { h, Component } from 'preact';
import _ from './utils'
var customAttrs = ['unload']
var staticProps = customAttrs.concat(['src', 'type', 'async', 'integrity', 'text', 'crossorigin'])
export default class PreactScript2 extends Component {
constructor(props) {
super(props);
this.state = {
installed: false,
loaded: {},
p: Promise.resolve()
}
this.loadExternalScript.bind(this);
this.insertInlineScript.bind(this);
}
insertInlineScript () {
const s = document.createElement('script')
// get inline script
let h = this.props.inlineScript
if (h) {
h = h.replace(/</gi, '<').replace(/>/gi, '>').replace(/&/gi, '&')
s.type = 'text/javascript'
s.appendChild(document.createTextNode(h))
this.base.parentElement.appendChild(s)
}
}
loadExternalScript (src, opts = { parent: document.head }) {
const __self = this
const promiseLoadScript = new Promise(function (resolve, reject) {
let s = document.createElement('script')
_.defaults2(s, _.omit(opts, ['unload', 'parent']), {type: 'text/javascript'})
s.async = false
s.src = src
if (opts.crossorigin) {
s.crossOrigin = opts.crossorigin
}
s.onload = () => {
const loaded = Object.assign({}, __self.loaded, {
[src]: 1
})
__self.setState({
loaded
})
resolve(src);
}
s.onerror = () => reject(new Error(src))
if (!__self.state.loaded[src]) {
opts.parent.appendChild(s)
}
})
return __self.state.loaded[src] ? Promise.resolve(src) : promiseLoadScript
}
componentDidMount() {
const __self = this
const __el = __self.base
const parent = __el.parentElement
if (!this.props.src) {
this.insertInlineScript()
} else {
let opts = _.omitBy(_.pick(this, staticProps), _.isUndefined)
opts.parent = parent
const loadFn = () => this.loadExternalScript(this.props.src, opts)
if (_.isUndefined(this.props.async)) {
this.setState({
p: this.state.p.then(loadFn)
})
} else {
loadFn()
}
}
this.setState({
installed: true
})
// destroy itself
parent.removeChild(__el)
}
componentWillUnmount() {
}
static getDerivedStateFromProps(props, state) {
}
render() {
return (
<div style="display:none" preact-script2></div>
);
}
}