vtils
Version:
一个面向业务的 JavaScript/TypeScript 实用程序库。
133 lines (131 loc) • 3.6 kB
JavaScript
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.LoadResourceUrlType = void 0;
exports.loadResource = loadResource;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
/**
* 资源类型。
*
* @public
*/
var LoadResourceUrlType = exports.LoadResourceUrlType = /*#__PURE__*/function (LoadResourceUrlType) {
LoadResourceUrlType["css"] = "css";
LoadResourceUrlType["cssText"] = "cssText";
LoadResourceUrlType["js"] = "js";
LoadResourceUrlType["jsText"] = "jsText";
LoadResourceUrlType["img"] = "img";
return LoadResourceUrlType;
}({});
/**
* 资源地址。
*
* @public
*/
function loadSpecificResource(url) {
return new Promise(function (resolve, reject) {
var el;
switch (url.type) {
case LoadResourceUrlType.js:
{
var _el = document.createElement('script');
_el.src = url.path;
_el.async = true;
el = _el;
}
break;
case LoadResourceUrlType.jsText:
{
var _el2 = document.createElement('script');
_el2.setAttribute('type', 'text/javascript');
_el2.textContent = url.path;
el = _el2;
}
break;
case LoadResourceUrlType.css:
{
var _el3 = document.createElement('link');
_el3.rel = 'stylesheet';
_el3.href = url.path;
el = _el3;
}
break;
case LoadResourceUrlType.cssText:
{
var _el4 = document.createElement('style');
_el4.setAttribute('type', 'text/css');
_el4.textContent = url.path;
el = _el4;
}
break;
case LoadResourceUrlType.img:
{
var _el5 = document.createElement('img');
_el5.src = url.path;
el = _el5;
}
break;
/* istanbul ignore next */
default:
break;
}
if (url.hook) {
url.hook(el);
}
el.onload = function () {
return resolve(el);
};
el.onerror = function () {
if (url.alternatePath) {
loadSpecificResource({
type: url.type,
path: url.alternatePath
}).then(resolve, reject);
} else {
reject(el);
}
};
if (url.type !== LoadResourceUrlType.img) {
document.head.appendChild(el);
}
});
}
/**
* 加载图片、代码、样式等资源。
*
* @public
* @param url 要加载的资源地址
* @param options 选项
* @returns 返回各资源的 HTML 元素组成的数组
* @example
* ```typescript
* loadResource([
* 'https://foo.bar/all.js',
* 'https://foo.bar/all.css',
* 'https://foo.bar/logo.png',
* {
* type: LoadResourceUrlType.js,
* path: 'https://s1.foo.bar/js/full',
* alternatePath: 'https://s2.foo.bar/js/full',
* },
* ]).then(() => {
* // 资源加载完成后的操作
* })
* ```
*/
function loadResource(url, options) {
var urls = (Array.isArray(url) ? url : [url]).map(function (item) {
return !(typeof item === 'string') ? item : {
type: /\.css$/i.test(item) ? LoadResourceUrlType.css : /\.(png|jpg|jpeg|gif|svg)$/i.test(item) ? LoadResourceUrlType.img : LoadResourceUrlType.js,
path: item
};
});
return Promise.all(urls.map(function (url) {
return loadSpecificResource((0, _extends2.default)({}, url, {
hook: function hook(el) {
options == null || options.hook == null || options.hook(el);
url.hook == null || url.hook(el);
}
}));
}));
}
;