Skip to content

Commit

Permalink
feat(loadResource): 支持 hook
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jul 30, 2021
1 parent 95dac32 commit 2473759
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/utils/loadResource.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { loadResource, LoadResourceUrlType } from './loadResource'

describe(loadResource.name, () => {
describe('loadResource', () => {
const createElement = document.createElement.bind(document)
beforeAll(() => {
jest.spyOn(document, 'createElement').mockImplementation((tag: string) => {
Expand Down Expand Up @@ -120,9 +120,23 @@ describe(loadResource.name, () => {
expect(document.documentElement.outerHTML).toInclude(src)
})

test('样式资源不插入 DOM', async () => {
test('图片资源不插入 DOM', async () => {
const src = 'http://foo.bar/this-is-an-image.jpg'
await loadResource(src)
expect(document.documentElement.outerHTML).not.toInclude(src)
})

test('支持 hook', async () => {
const src = 'http://foo.bar/this-is-an-image.js'
await loadResource({
type: LoadResourceUrlType.js,
path: src,
hook: el => {
el.dataset.hooked = '1'
},
})
expect(
document.documentElement.querySelector(`[data-hooked="1"]`)!.tagName,
).toBe('SCRIPT')
})
})
6 changes: 6 additions & 0 deletions src/utils/loadResource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ export interface LoadResourceUrl {

/** 备用资源路径 */
alternatePath?: string

/** 钩子 */
hook?: (el: HTMLScriptElement | HTMLLinkElement | HTMLImageElement) => any
}

function loadSpecificResource(
Expand All @@ -55,6 +58,9 @@ function loadSpecificResource(
default:
break
}
if (url.hook) {
url.hook(el)
}
el.onload = () => resolve(el)
el.onerror = () => {
if (url.alternatePath) {
Expand Down

0 comments on commit 2473759

Please sign in to comment.