export const loadResourceInHead = (src) => {
return new Promise((resolve, reject) => {
if (!src) {
reject('The src cannot be empty!');
return;
}
if (src.startsWith('/')) {
// src = endpoints.ui + src;
}
let suffix = src.substring(src.lastIndexOf('.') + 1);
if (suffix.indexOf('?') >= 0) {
suffix = suffix.substring(0, suffix.indexOf('?'));
// eslint-disable-next-line no-undef
src += '&hash=' + __webpack_hash__;
} else {
// eslint-disable-next-line no-undef
src += '?' + __webpack_hash__;
}
const isScript = suffix.toLowerCase() === 'js';
const tagName = isScript ? 'script' : 'link';
const loadedTag = document.head.querySelector(tagName + "[" + (isScript ? "src" : "href") + "^='" + src + "']");
if (loadedTag) {
if (loadedTag.ready) {
resolve();
return;
}
const oldOnload = loadedTag.onload;
loadedTag.onload = function (res) {
oldOnload && oldOnload();
resolve(res);
};
return;
}
const tag = document.createElement(tagName);
tag.type = isScript ? 'text/javascript' : 'text/css';
tag[isScript ? 'src' : 'href'] = src;
if (!isScript) {
tag.rel = 'stylesheet';
}
document.head.appendChild(tag);
$$.loading(true);
tag.onload = function (res) {
$$.loading(false);
tag.ready = true;
resolve(res);
};
tag.onerror = function (error) {
$$.loading(false);
reject(error);
};
});
};
用法:
window.promiseAll(
utils.loadResourceInHead("ckeditor.js"),
utils.loadResourceInHead("math.js"),
utils.loadResourceInHead("music.js"),
).then(() => {
if (!RichEditor.loaded) {
RichEditor.loaded = true;
}
this.setState({ loaded: true });
});
评论 (0)