This repository was archived by the owner on Apr 26, 2019. It is now read-only.
forked from LasaleFamine/polymer-lib-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib-loader.es6.js
More file actions
93 lines (81 loc) · 2.06 KB
/
lib-loader.es6.js
File metadata and controls
93 lines (81 loc) · 2.06 KB
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
'use strict'
const Polymer = window.Polymer
const CustomEvent = window.CustomEvent
class libLoader {
// Define behaviors with a getter.
get behaviors () {
return []
}
// Element setup goes in beforeRegister instead of createdCallback.
beforeRegister () {
this.is = 'lib-loader'
// Define the properties object in beforeRegister.
this.properties = {
/** Link of the library */
lib: {
type: String
},
/** <script id="" */
libUniqueId: {
type: String
},
/** True when the lib is ready */
libReady: {
type: Boolean,
value: false,
reflectToAttribute: true
}
}
}
// on ready try to insert the lib on the page
attached () {
if (!this.lib || !this.libUniqueId) {
console.error('<lib-loader> ERROR: Library or unique id not specified.')
return false
}
this.addEventListener('lib-loaded', (evt) => {
this.set('libReady', true)
})
this._insertLib(this.lib, this.libUniqueId)
}
detached () {
this.removeLib()
}
/** Remove lib from the dom */
removeLib () {
let lib = document.querySelector('#' + this.libUniqueId)
lib ? lib.remove() : null
}
/** ===============
* Private methods
**/
/* Insert at the end of the body the js lib */
_insertLib (link, type) {
// Check for existent lib
if (document.querySelector('#' + type)) {
document.querySelector('lib-loader').addEventListener('lib-loaded', (evt) => {
this._onLoadLib(evt, type)
})
return false
}
let src = document.createElement('script')
src.setAttribute('src', link)
src.id = type
src.async = true
src.onreadystatechange = src.onload = (evt) => {
this._onLoadLib(evt, type)
}
document.body.appendChild(src)
}
/** ===============
* Event listeners
**/
/* On lib loaded */
_onLoadLib (evt, type) {
setTimeout(() => {
this.dispatchEvent(new CustomEvent('lib-loaded'))
})
}
}
// Register the element using Polymer's constructor.
Polymer(libLoader)