-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
57 lines (41 loc) · 1.38 KB
/
index.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
const VuePreload = {}
const validateAs = type => ['', 'script', 'style', 'image', 'media', 'document', 'font'].indexOf(type) > -1
const domTokenListSupports = function() {
try {
return document.createElement('link').relList.supports('preload')
} catch (e) {
// link[rel=preload] is not supported
}
}
VuePreload.install = function(Vue) {
let isSupported;
const init = function(){
isSupported = domTokenListSupports();
if(!isSupported) console.info('Current browser does not support link[rel=preload] functionality')
}
Vue.addPreloadLink = function(elementHref, elementAs) {
if (!isSupported) return
if (elementAs === undefined) elementAs = 'script'
if (!validateAs(elementAs)) return
const lnk = document.createElement('link')
const rel = document.createAttribute('rel')
rel.value = 'preload'
lnk.setAttributeNode(rel)
const as = document.createAttribute('as')
as.value = elementAs
lnk.setAttributeNode(as)
const href = document.createAttribute('href')
href.value = elementHref
lnk.setAttributeNode(href)
document.head.appendChild(lnk)
}
Vue.preloadGroup = function(resourcesMap) {
for (const [key, value] of Object.entries(resourcesMap)) {
if (validateAs(key) && value.length) {
value.forEach(item => Vue.addPreloadLink(item, key))
}
}
}
init()
}
export default VuePreload