simulate document currentScript while dynamic loading (#899)

This commit is contained in:
Kuitos 2020-08-26 11:32:24 +08:00 committed by GitHub
parent c07e9536d6
commit 7a538cce9f
2 changed files with 14 additions and 2 deletions

View File

@ -61,7 +61,7 @@
"homepage": "https://github.com/kuitos/qiankun#readme",
"dependencies": {
"@babel/runtime": "^7.10.5",
"import-html-entry": "^1.8.1",
"import-html-entry": "^1.9.0",
"lodash": "^4.17.11",
"single-spa": "^5.3.1",
"tslib": "^1.10.0"

View File

@ -76,7 +76,7 @@ function getOverwrittenAppendChildOrInsertBefore(opts: {
newChild: T,
refChild?: Node | null,
) {
const element = newChild as any;
let element = newChild as any;
const { rawDOMAppendOrInsertBefore } = opts;
if (element.tagName) {
// eslint-disable-next-line prefer-const
@ -152,6 +152,14 @@ function getOverwrittenAppendChildOrInsertBefore(opts: {
execScripts(null, [src], proxy, {
fetch,
strictGlobal: !singular,
beforeExec: () => {
Object.defineProperty(document, 'currentScript', {
get(): any {
return element;
},
configurable: true,
});
},
success: () => {
// we need to invoke the onload event manually to notify the event listener that the script was completed
// here are the two typical ways of dynamic script loading
@ -163,6 +171,8 @@ function getOverwrittenAppendChildOrInsertBefore(opts: {
} else {
element.dispatchEvent(loadEvent);
}
element = null;
},
error: () => {
const errorEvent = new CustomEvent('error');
@ -171,6 +181,8 @@ function getOverwrittenAppendChildOrInsertBefore(opts: {
} else {
element.dispatchEvent(errorEvent);
}
element = null;
},
});