Skip to content
This repository was archived by the owner on Feb 22, 2021. It is now read-only.

Commit 7cf71c6

Browse files
committed
refactor(loader): improve script filter
1 parent 2b994a7 commit 7cf71c6

File tree

2 files changed

+20
-21
lines changed

2 files changed

+20
-21
lines changed

src/core/loader.ts

Lines changed: 3 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,13 @@
11
import { EventHub } from './event'
22
import { LoaderEvent } from '../types'
3-
import { $fetch, isRelativeURL } from '../utils/tools'
3+
import { $fetch, filterResources } from '../utils/tools'
44

55

66
export class Loader {
77

88
hub: EventHub
99
readonly baseEvent: LoaderEvent = { source: '', type: 'none', success: true, insertScripts: () => {} }
1010

11-
static resourceReg(str: string): RegExp {
12-
return {
13-
script: /\<script\s+\S?src\=\"([^"]*)\"/g,
14-
}[str]
15-
}
16-
1711
constructor(hub: EventHub) {
1812
this.hub = hub
1913
}
@@ -30,26 +24,15 @@ export class Loader {
3024
urls.forEach(url => {
3125
$fetch(url, { mode: 'cors' })
3226
.then(html => {
33-
console.log(html)
34-
this.scripts(this.filterResources(html, 'script'))
27+
this.scripts(filterResources(html, 'script'))
28+
this.styles(filterResources(html, 'style'))
3529
})
3630
.catch((e) => {
3731
console.log(e)
3832
})
3933
})
4034
}
4135

42-
private filterResources(source: string, type: string): string[] {
43-
const reg: RegExp = Loader.resourceReg(type), arr: string[] = []
44-
let result: string[], num = 10
45-
while ((result = reg.exec(source)) && num --) {
46-
if (result[1] && !isRelativeURL(result[1])) {
47-
arr.push(result[1])
48-
}
49-
}
50-
return arr
51-
}
52-
5336
private loadURL(urls: string[], type: string): void {
5437
urls.forEach(url => {
5538
const scriptEvent = Object.assign({}, this.baseEvent, {

src/utils/tools.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11

2-
32
export const $fetch = (url: string, init: RequestInit = {}) => {
43
return fetch(url, Object.assign({ mode: 'no-cors' }, init))
54
.then(r => {
@@ -11,3 +10,20 @@ export const $fetch = (url: string, init: RequestInit = {}) => {
1110
export const isRelativeURL = (path: string) => {
1211
return path.startsWith('./') || path.startsWith('..')
1312
}
13+
14+
export const makeResourceReg = (str: string): RegExp => {
15+
return {
16+
script: /\<script\s+\S?src\=\"([^"]*)\"/g,
17+
style: /\<link\s+\S?\s?href\=\"([^"]*.css)\"/,
18+
}[str]
19+
}
20+
export const filterResources = (source: string, type: string): string[] => {
21+
const reg: RegExp = makeResourceReg(type), arr: string[] = []
22+
let result: string[], num = 10
23+
while ((result = reg.exec(source)) && num --) {
24+
if (result[1] && !isRelativeURL(result[1])) {
25+
arr.push(result[1])
26+
}
27+
}
28+
return arr
29+
}

0 commit comments

Comments
 (0)