/
preload-assets.js
58 lines (44 loc) · 1.67 KB
/
preload-assets.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
const isStructureEqual = (pathname, path) => {
const pathnameParts = pathname.split('/')
const pathParts = path.split('/')
if (pathnameParts.length !== pathParts.length) return false
return pathnameParts.every((part, ind) => part === pathParts[ind] || pathParts[ind].startsWith(':'))
}
const getDynamicProperties = (pathname, path) => {
const pathParts = path.split('/')
const pathnameParts = pathname.split('/')
const dynamicProperties = {}
for (let i = 0; i < pathParts.length; i++) {
if (pathParts[i].startsWith(':')) dynamicProperties[pathParts[i].slice(1)] = pathnameParts[i]
}
return dynamicProperties
}
let { pathname } = window.location
if (pathname !== '/') pathname = pathname.replace(/\/$/, '')
for (const { path, scripts, data } of pages) {
const match = pathname === path || (path.includes(':') && isStructureEqual(pathname, path))
if (!match) continue
scripts.forEach(script => {
document.head.appendChild(
Object.assign(document.createElement('link'), { rel: 'preload', href: '/' + script, as: 'script' })
)
})
if (!data) break
data.forEach(({ url, crossorigin, preconnectURL }) => {
if (url.startsWith('func:')) url = eval(url.replace('func:', ''))
const fullURL = typeof url === 'string' ? url : url(getDynamicProperties(pathname, path))
document.head.appendChild(
Object.assign(document.createElement('link'), {
rel: 'preload',
href: fullURL,
as: 'fetch',
crossOrigin: crossorigin
})
)
if (preconnectURL) {
document.head.appendChild(
Object.assign(document.createElement('link'), { rel: 'preconnect', href: preconnectURL })
)
}
})
}