resource-preloader 2.0.4 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/resource-loader.amd.js +4 -4
  2. package/dist/resource-loader.amd.js.map +1 -1
  3. package/dist/resource-loader.amd.min.js.map +1 -1
  4. package/dist/resource-loader.cjs.js +4 -4
  5. package/dist/resource-loader.cjs.js.map +1 -1
  6. package/dist/resource-loader.cjs.min.js.map +1 -1
  7. package/dist/resource-loader.esm.js +2 -2
  8. package/dist/resource-loader.esm.js.map +1 -1
  9. package/dist/resource-loader.esm.min.js +1 -1
  10. package/dist/resource-loader.esm.min.js.map +1 -1
  11. package/dist/resource-loader.umd.js +4 -4
  12. package/dist/resource-loader.umd.js.map +1 -1
  13. package/dist/resource-loader.umd.min.js.map +1 -1
  14. package/dist/resource-preloader.amd.js +386 -362
  15. package/dist/resource-preloader.amd.js.map +1 -1
  16. package/dist/resource-preloader.amd.min.js +1 -1
  17. package/dist/resource-preloader.amd.min.js.map +1 -1
  18. package/dist/resource-preloader.cjs.js +292 -268
  19. package/dist/resource-preloader.cjs.js.map +1 -1
  20. package/dist/resource-preloader.cjs.min.js +1 -1
  21. package/dist/resource-preloader.cjs.min.js.map +1 -1
  22. package/dist/resource-preloader.esm.js +292 -268
  23. package/dist/resource-preloader.esm.js.map +1 -1
  24. package/dist/resource-preloader.esm.min.js +1 -1
  25. package/dist/resource-preloader.esm.min.js.map +1 -1
  26. package/dist/resource-preloader.umd.js +389 -365
  27. package/dist/resource-preloader.umd.js.map +1 -1
  28. package/dist/resource-preloader.umd.min.js +1 -1
  29. package/dist/resource-preloader.umd.min.js.map +1 -1
  30. package/package.json +4 -3
  31. package/src/checker.js +53 -0
  32. package/src/config.js +10 -12
  33. package/src/index.js +5 -5
  34. package/src/loader.js +128 -128
  35. package/src/other.js +4 -4
  36. package/src/scheduler.js +123 -149
  37. package/types/index.d.ts +20 -8
@@ -1,398 +1,422 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
- typeof define === 'function' && define.amd ? define(factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.ResourceLoader = factory());
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
+ typeof define === 'function' && define.amd ? define(factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.resourcePreloader = factory());
5
5
  })(this, (function () { 'use strict';
6
6
 
7
- // 默认公共配置
8
- const defaultConfig = {
9
- timeout: 1000, // 默认超时时间1s
10
- retry: 0, // 默认不重试
11
- };
12
-
13
- /** @var {GlobalConfig} */
14
- let globalConfig = { ...defaultConfig };
15
-
16
- /**
17
- * 配置公共配置的方法(导出)
18
- * @param {GlobalConfig} config - 需覆盖的公共配置
19
- * @returns {GlobalConfig} 合并后的最终全局配置
20
- */
21
- function setGlobalConfig(config) {
22
- if (typeof config !== 'object' || config === null) {
23
- throw new Error('配置参数必须是一个非空对象');
24
- }
25
- globalConfig = { ...globalConfig, ...config };
26
- return { ...globalConfig };
7
+ // 默认公共配置
8
+ const defaultConfig = {
9
+ timeout: 1500, // 默认超时时间1s
10
+ retry: 0, // 默认不重试
11
+ };
12
+
13
+ /** @var {GlobalConfig} */
14
+ let globalConfig = { ...defaultConfig };
15
+
16
+ /**
17
+ * 配置公共配置的方法(导出)
18
+ * @param {GlobalConfig} config - 需覆盖的公共配置
19
+ * @returns {GlobalConfig} 合并后的最终全局配置
20
+ */
21
+ function setGlobalConfig(config) {
22
+ if (typeof config !== "object" || config === null) {
23
+ throw new Error("配置参数必须是一个非空对象");
27
24
  }
25
+ globalConfig = { ...globalConfig, ...config };
26
+ return { ...globalConfig };
27
+ }
28
+
29
+ /**
30
+ * 获取当前全局配置
31
+ * @returns {GlobalConfig} 全局配置
32
+ */
33
+ function getGlobalConfig() {
34
+ return { ...globalConfig };
35
+ }
36
+
37
+ // 加载器映射表(存储内置+自定义加载器)
38
+ const loaderMap = new Map();
39
+
40
+ /**
41
+ * 通用资源加载Promise封装
42
+ * @param {string} url - 资源地址
43
+ * @param {string} type - 具体的资源加载处理函数
44
+ * @param {number} timeout - 超时时间
45
+ * @returns {Promise<LoadResult>} 加载结果Promise
46
+ */
47
+ function wrapLoadPromise(url, type, timeout) {
48
+ return new Promise(function (resolve, reject) {
49
+ // 获取加载器处理函数
50
+ const handler = getLoader(type);
51
+ // 超时处理
52
+ const timeoutTimer = setTimeout(() => {
53
+ reject(new Error(`Resource ${url} load timeout (${timeout}ms)`));
54
+ }, timeout);
55
+
56
+ // 执行具体加载逻辑
57
+ handler(url)
58
+ .then(function (result) {
59
+ clearTimeout(timeoutTimer);
60
+ resolve({
61
+ url,
62
+ success: true,
63
+ data: result,
64
+ error: null,
65
+ });
66
+ })
67
+ .catch(function (error) {
68
+ clearTimeout(timeoutTimer);
69
+ reject({
70
+ url,
71
+ success: false,
72
+ data: null,
73
+ error,
74
+ });
75
+ });
76
+ });
77
+ }
28
78
 
79
+ /** 初始化内置加载器 **/
80
+ // --------------- 内置JS加载器 ---------------
81
+ loaderMap.set(
82
+ "js",
29
83
  /**
30
- * 获取当前全局配置
31
- * @returns {GlobalConfig} 全局配置
84
+ * JS加载器
85
+ * @param {string} url
86
+ * @returns {Promise<HTMLScriptElement|void>}
32
87
  */
33
- function getGlobalConfig() {
34
- return { ...globalConfig };
35
- }
36
-
37
- // 加载器映射表(存储内置+自定义加载器)
38
- const loaderMap = new Map();
88
+ function (url) {
89
+ const script = document.createElement("script");
90
+ return new Promise(function (resolve, reject) {
91
+ script.type = "text/javascript";
92
+ script.src = url;
93
+ script.async = false; // 保持加载顺序(不开启异步)
94
+ script.dataset.flag = "resource-preloader";
95
+
96
+ script.addEventListener("load", function (e) {
97
+ resolve(script);
98
+ });
99
+ script.addEventListener("error", function () {
100
+ reject(new Error(`JS resource ${url} load failed`));
101
+ });
39
102
 
103
+ document.head.appendChild(script);
104
+ }).finally(function () {
105
+ // 加载完成后移除标签,避免污染DOM
106
+ document.head.removeChild(script);
107
+ });
108
+ },
109
+ );
110
+ // --------------- 内置CSS加载器 ---------------
111
+ loaderMap.set(
112
+ "css",
40
113
  /**
41
- * 通用资源加载Promise封装
42
- * @param {string} url - 资源地址
43
- * @param {string} type - 具体的资源加载处理函数
44
- * @param {number} timeout - 超时时间
45
- * @returns {Promise<LoadResult>} 加载结果Promise
114
+ * CSS加载器
115
+ * @param {string} url
116
+ * @returns {Promise<HTMLLinkElement>}
46
117
  */
47
- function wrapLoadPromise(url, type, timeout) {
48
- return new Promise(function (resolve, reject) {
49
- // 获取加载器处理函数
50
- const handler = getLoader(type);
51
- // 超时处理
52
- const timeoutTimer = setTimeout(() => {
53
- reject(new Error(`Resource ${url} load timeout (${timeout}ms)`));
54
- }, timeout);
55
-
56
- // 执行具体加载逻辑
57
- handler(url)
58
- .then(function (result) {
59
- clearTimeout(timeoutTimer);
60
- resolve({
61
- url,
62
- success: true,
63
- data: result,
64
- error: null,
65
- });
66
- })
67
- .catch(function (error) {
68
- clearTimeout(timeoutTimer);
69
- reject({
70
- url,
71
- success: false,
72
- data: null,
73
- error,
74
- });
75
- });
118
+ function (url) {
119
+ return new Promise(function (resolve, reject) {
120
+ const link = document.createElement("link");
121
+ link.rel = "stylesheet";
122
+ link.href = url;
123
+ link.dataset.flag = "resource-preloader";
124
+
125
+ link.addEventListener("load", function () {
126
+ resolve(link);
76
127
  });
77
- }
78
-
79
- /** 初始化内置加载器 **/
80
- // --------------- 内置JS加载器 ---------------
81
- loaderMap.set(
82
- 'js',
83
- /**
84
- * JS加载器
85
- * @param {string} url
86
- * @returns {Promise<HTMLScriptElement|void>}
87
- */
88
- function (url) {
89
- const script = document.createElement('script');
90
- return new Promise(function (resolve, reject) {
91
- script.type = 'text/javascript';
92
- script.src = url;
93
- script.async = false; // 保持加载顺序(不开启异步)
94
- script.dataset.flag = 'resource-preloader';
95
-
96
- script.addEventListener('load', function (e) {
97
- resolve(script);
98
- });
99
- script.addEventListener('error', function () {
100
- reject(new Error(`JS resource ${url} load failed`));
101
- });
102
-
103
- document.head.appendChild(script);
104
- }).finally(function () {
105
- // 加载完成后移除标签,避免污染DOM
106
- document.head.removeChild(script);
107
- });
108
- }
109
- );
110
- // --------------- 内置CSS加载器 ---------------
111
- loaderMap.set(
112
- 'css',
113
- /**
114
- * CSS加载器
115
- * @param {string} url
116
- * @returns {Promise<HTMLLinkElement>}
117
- */
118
- function (url) {
119
- return new Promise(function (resolve, reject) {
120
- const link = document.createElement('link');
121
- link.rel = 'stylesheet';
122
- link.href = url;
123
- link.dataset.flag = 'resource-preloader';
124
-
125
- link.addEventListener('load', function () {
126
- resolve(link);
127
- });
128
- link.addEventListener('error', function () {
129
- reject(new Error(`CSS resource ${url} load failed`));
130
- document.head.removeChild(link);
131
- });
132
- document.head.appendChild(link);
133
- });
134
- }
135
- );
136
- // --------------- 内置IMG加载器 ---------------
137
- loaderMap.set(
138
- 'img',
139
- /**
140
- * 图片加载器
141
- * @param url
142
- * @returns {Promise<HTMLImageElement>}
143
- */
144
- function (url) {
145
- const img = new Image();
146
- img.dataset.flag = 'resource-preloader';
147
- return new Promise(function (resolve, reject) {
148
- img.addEventListener('load', function () {
149
- resolve(img);
150
- });
151
- img.addEventListener('error', function () {
152
- reject(new Error(`IMG resource ${url} load failed`));
153
- });
154
- // img 标签不需要添加到DOM树
155
- img.src = url;
156
- });
157
- }
158
- );
159
- // --------------- 内置JSON加载器 ---------------
160
- loaderMap.set(
161
- 'json',
162
- /**
163
- * JSON加载器
164
- * @param {string} url
165
- * @returns {Promise<Object|Array|null|undefined>}
166
- */
167
- function (url) {
168
- return fetch(url)
169
- .then(function (res) {
170
- if (!res.ok) {
171
- throw new Error(`JSON resource ${url} load failed`);
172
- }
173
- return res.json();
174
- })
175
- .catch(function (error) {
176
- throw new Error(`JSON resource ${url} load failed: ${error.message}`);
177
- });
178
- }
179
- );
180
-
128
+ link.addEventListener("error", function () {
129
+ reject(new Error(`CSS resource ${url} load failed`));
130
+ document.head.removeChild(link);
131
+ });
132
+ document.head.appendChild(link);
133
+ });
134
+ },
135
+ );
136
+ // --------------- 内置IMG加载器 ---------------
137
+ loaderMap.set(
138
+ "img",
181
139
  /**
182
- * 注册自定义加载器的方法
183
- * @param {string} type - 资源类型(唯一标识)
184
- * @param {LoaderHandler} handler - 加载处理函数,接收url参数,返回Promise
140
+ * 图片加载器
141
+ * @param url
142
+ * @returns {Promise<HTMLImageElement>}
185
143
  */
186
- function registerLoader(type, handler) {
187
- if (typeof type !== 'string' || type.trim() === '') {
188
- throw new Error('资源类型必须是非空字符串');
189
- }
190
- const _ = Object.prototype.toString.call(type).slice(8, -1);
191
- if (['Function', 'AsyncFunction'].includes(_)) {
192
- throw new Error('加载器必须是一个函数返回Promise对象或一个异步函数');
193
- }
194
- if (loaderMap.has(type)) {
195
- console.warn(`类型为${type}的加载器已存在,将被覆盖`);
196
- }
197
- loaderMap.set(type, handler);
198
- }
199
-
144
+ function (url) {
145
+ const img = new Image();
146
+ img.dataset.flag = "resource-preloader";
147
+ return new Promise(function (resolve, reject) {
148
+ img.addEventListener("load", function () {
149
+ resolve(img);
150
+ });
151
+ img.addEventListener("error", function () {
152
+ reject(new Error(`IMG resource ${url} load failed`));
153
+ });
154
+ // img 标签不需要添加到DOM树
155
+ img.src = url;
156
+ });
157
+ },
158
+ );
159
+ // --------------- 内置JSON加载器 ---------------
160
+ loaderMap.set(
161
+ "json",
200
162
  /**
201
- * 获取对应类型的加载器
202
- * @param {string} type - 资源类型
203
- * @returns {Function} 加载器处理函数
163
+ * JSON加载器
164
+ * @param {string} url
165
+ * @returns {Promise<Object|Array|null|undefined>}
204
166
  */
205
- function getLoader(type) {
206
- if (!loaderMap.has(type)) {
207
- throw new Error(`未找到${type}类型的加载器,请先注册自定义加载器`);
208
- }
209
- return loaderMap.get(type);
167
+ function (url) {
168
+ return fetch(url)
169
+ .then(function (res) {
170
+ if (!res.ok) {
171
+ throw new Error(`JSON resource ${url} load failed`);
172
+ }
173
+ return res.json();
174
+ })
175
+ .catch(function (error) {
176
+ throw new Error(`JSON resource ${url} load failed: ${error.message}`);
177
+ });
178
+ },
179
+ );
180
+
181
+ /**
182
+ * 注册自定义加载器的方法
183
+ * @param {string} type - 资源类型(唯一标识)
184
+ * @param {LoaderHandler} handler - 加载处理函数,接收url参数,返回Promise
185
+ */
186
+ function registerLoader(type, handler) {
187
+ if (typeof type !== "string" || type.trim() === "") {
188
+ throw new Error("资源类型必须是非空字符串");
210
189
  }
211
-
212
- /**
213
- * 检测循环依赖(深度优先遍历,配置字段改为dependencies)
214
- * @param {Array} configList - 完整配置数组
215
- * @param {number} currentId - 当前资源ID
216
- * @param {Set} visited - 已访问的资源ID集合
217
- * @param {Set} visiting - 正在访问的资源ID集合(用于检测环)
218
- */
219
- function detectCycle(configList, currentId, visited, visiting) {
220
- const currentConfig = configList.find(item => item.name === currentId);
221
- if (!currentConfig) {
222
- throw new Error(`未找到ID为${currentId}的资源配置`);
223
- }
224
-
225
- // 若正在访问中,说明存在循环依赖
226
- if (visiting.has(currentId)) {
227
- throw new Error(`检测到循环依赖:${Array.from(visiting).join(' -> ')} -> ${currentId}`);
228
- }
229
-
230
- // 若已访问过,直接返回(无需重复检测)
231
- if (visited.has(currentId)) {
232
- return;
233
- }
234
-
235
- // 标记为正在访问
236
- visiting.add(currentId);
237
- // 递归检测依赖项(改为dependencies)
238
- const dependencies = currentConfig.dependencies || [];
239
- for (const depId of dependencies) {
240
- detectCycle(configList, depId, visited, visiting);
241
- }
242
- // 标记为已访问,移出正在访问集合
243
- visiting.delete(currentId);
244
- visited.add(currentId);
190
+ const _ = Object.prototype.toString.call(type).slice(8, -1);
191
+ if (["Function", "AsyncFunction"].includes(_)) {
192
+ throw new Error("加载器必须是一个函数返回Promise对象或一个异步函数");
245
193
  }
246
-
247
- /**
248
- * 预检测所有资源的循环依赖(配置字段改为dependencies)
249
- * @param {Array} configList - 完整配置数组
250
- */
251
- function checkAllCycles(configList) {
252
- const visited = new Set();
253
- for (const config of configList) {
254
- detectCycle(configList, config.name, visited, new Set());
255
- }
194
+ if (loaderMap.has(type)) {
195
+ console.warn(`类型为${type}的加载器已存在,将被覆盖`);
256
196
  }
257
-
258
- /**
259
- * 递归加载单个资源及其所有依赖(保证依赖先加载,配置字段改为dependencies)
260
- * @param {string|number} name - 资源ID
261
- * @param {Array} configList - 完整配置数组
262
- * @param {number} timeout - 超时时间
263
- * @param {Map} loadedMap - 已加载资源的结果缓存
264
- * @returns {Promise<ResourceLoadResult>} 加载结果
265
- */
266
- async function loadResourceWithDeps(name, configList, timeout, loadedMap) {
267
- // 若已加载,直接返回缓存结果
268
- if (loadedMap.has(name)) {
269
- return loadedMap.get(name);
270
- }
271
-
272
- const currentConfig = configList.find(item => item.name === name);
273
- if (!currentConfig) {
274
- throw new Error(`未找到name为${name}的资源配置`);
275
- }
276
-
277
- // 1. 先加载所有依赖(改为dependencies)
278
- const dependencies = currentConfig.dependencies || [];
279
- for (const _ of dependencies) {
280
- await loadResourceWithDeps(_, configList, timeout, loadedMap);
281
- }
282
-
283
- // 2. 再加载当前资源的urls(顺序加载,一个成功即可)
284
- const {urls, type} = currentConfig;
285
- let loadResult = null;
286
- let status = 'success';
287
- let error = null;
288
-
289
- try {
290
- loadResult = await loadUrlsInOrder(urls, type, timeout);
291
- } catch (err) {
292
- status = 'failed';
293
- error = err;
294
- }
295
-
296
- // 3. 缓存加载结果
297
- const result = {
298
- name,
299
- config: currentConfig,
300
- result:loadResult,
301
- status,
302
- error,
303
- };
304
- loadedMap.set(name, result);
305
- return result;
197
+ loaderMap.set(type, handler);
198
+ }
199
+
200
+ /**
201
+ * 获取对应类型的加载器
202
+ * @param {string} type - 资源类型
203
+ * @returns {Function} 加载器处理函数
204
+ */
205
+ function getLoader(type) {
206
+ if (!loaderMap.has(type)) {
207
+ throw new Error(`未找到${type}类型的加载器,请先注册自定义加载器`);
208
+ }
209
+ return loaderMap.get(type);
210
+ }
211
+
212
+ /**
213
+ * 预检测所有资源的循环依赖
214
+ * @param {Array<FullResourceConfig>} configList - 完整配置数组
215
+ */
216
+ function checkDependencies (configList) {
217
+ // 预构建配置映射,O(n) 时间复杂度
218
+ const configMap = new Map(configList.map((config) => [config.name, config]));
219
+
220
+ const visited = new Set();
221
+ const visiting = new Set(); // 全局共享 visiting 集合
222
+
223
+ for (const config of configList) {
224
+ if (!visited.has(config.name)) {
225
+ detectCycle(configMap, config.name);
226
+ }
306
227
  }
307
-
308
228
  /**
309
- * 按顺序加载urls,只需要一个成功即可
310
- * @param {Array} urls - 资源地址数组
311
- * @param {string} type - 资源类型
312
- * @param {number} timeout - 超时时间
313
- * @returns {Promise<LoadResult>} 成功的加载结果
229
+ * 检测循环依赖
230
+ * @param {Map} configMap - 预构建的配置映射
231
+ * @param {string|number} currentId - 当前资源ID
314
232
  */
315
- async function loadUrlsInOrder(urls, type, timeout) {
316
- if (!Array.isArray(urls) || urls.length === 0) {
317
- throw new Error('urls必须是非空数组');
318
- }
233
+ function detectCycle(configMap, currentId) {
234
+ const currentConfig = configMap.get(currentId);
235
+ if (!currentConfig) {
236
+ throw new Error(`未找到ID为${currentId}的资源配置`);
237
+ }
238
+
239
+ // 若正在访问中,说明存在循环依赖
240
+ if (visiting.has(currentId)) {
241
+ throw new Error(
242
+ `检测到循环依赖:${Array.from(visiting).join(" -> ")} -> ${currentId}`,
243
+ );
244
+ }
245
+
246
+ // 若已访问过,直接返回
247
+ if (visited.has(currentId)) {
248
+ return;
249
+ }
250
+
251
+ // 标记为正在访问
252
+ visiting.add(currentId);
253
+
254
+ // 递归检测依赖项
255
+ const dependencies = currentConfig.dependencies || [];
256
+ for (const depId of dependencies) {
257
+ detectCycle(configMap, depId);
258
+ }
259
+
260
+ // 标记为已访问
261
+ visiting.delete(currentId);
262
+ visited.add(currentId);
263
+ }
264
+ }
265
+
266
+ /**
267
+ * 递归加载单个资源及其所有依赖(保证依赖先加载,配置字段改为dependencies)
268
+ * @param {string|number} name - 资源ID
269
+ * @param {Array} configList - 完整配置数组
270
+ * @param {number} timeout - 超时时间
271
+ * @param {Map} loadedMap - 已加载资源的结果缓存
272
+ * @returns {Promise<ResourceLoadResult>} 加载结果
273
+ */
274
+ async function loadResourceWithDeps(name, configList, timeout, loadedMap) {
275
+ // 若已加载,直接返回缓存结果
276
+ if (loadedMap.has(name)) {
277
+ return loadedMap.get(name);
278
+ }
319
279
 
320
- let lastError;
280
+ const currentConfig = configList.find((item) => item.name === name);
281
+ if (!currentConfig) {
282
+ throw new Error(`未找到name为${name}的资源配置`);
283
+ }
321
284
 
322
- // 按顺序遍历urls,直到有一个加载成功
323
- for (const url of urls) {
324
- try {
325
- return await wrapLoadPromise(url, type, timeout);
326
- } catch (error) {
327
- lastError = error; // 加载失败,继续下一个url
328
- }
329
- }
285
+ // 1. 先加载所有依赖(改为dependencies)
286
+ const dependencies = currentConfig.dependencies || [];
287
+ for (const _ of dependencies) {
288
+ await loadResourceWithDeps(_, configList, timeout, loadedMap);
289
+ }
330
290
 
331
- // 所有url都加载失败,抛出最后一个错误
332
- throw new Error(`所有${type}类型资源加载失败,最后一个错误:${lastError?.message || '未知错误'}`);
291
+ // 2. 再加载当前资源的urls(顺序加载,一个成功即可)
292
+ const { urls, type } = currentConfig;
293
+ let loadResult = null;
294
+ let status = "success";
295
+ let error = null;
296
+
297
+ try {
298
+ loadResult = await loadUrlsInOrder(name, urls, type, timeout);
299
+ } catch (err) {
300
+ status = "failed";
301
+ error = err;
333
302
  }
334
303
 
335
- /**
336
- * 核心加载调度方法(最终结果保持配置定义顺序)
337
- * @param {Array<ResourceConfig>} configList - 输入配置数组
338
- * @returns {Promise<ResourceLoadResult[]>} 按配置定义顺序的加载结果数组
339
- */
340
- async function resourcePreloader(configList) {
341
- if (!Array.isArray(configList) || configList.length === 0) {
342
- throw new Error('配置数组必须是非空数组');
304
+ // 3. 缓存加载结果
305
+ const result = {
306
+ name,
307
+ config: currentConfig,
308
+ result: loadResult,
309
+ status,
310
+ error,
311
+ };
312
+ loadedMap.set(name, result);
313
+ return result;
314
+ }
315
+
316
+ /**
317
+ * 按顺序加载urls,只需要一个成功即可
318
+ * @param {string} name - 资源名
319
+ * @param {Array<string>} urls - 资源地址数组
320
+ * @param {string} type - 资源类型
321
+ * @param {number} timeout - 超时时间
322
+ * @returns {Promise<LoadResult>} 成功的加载结果
323
+ */
324
+ async function loadUrlsInOrder(name, urls, type, timeout) {
325
+ if (!Array.isArray(urls) || urls.length === 0) {
326
+ throw new Error("urls必须是非空数组");
327
+ }
328
+ const errors = [];
329
+
330
+ // 按顺序遍历urls,直到有一个加载成功
331
+ for (const url of urls) {
332
+ try {
333
+ const ret = await wrapLoadPromise(url, type, timeout);
334
+ if (errors.length) {
335
+ console.warn(`加载${name}资源时的一些错误信息:`, errors);
343
336
  }
344
-
345
- // string[] 形式处理成 { name, urls, type } 形式
346
- configList = configList.map(item => {
347
- if (typeof item === 'string') {
348
- const url = new URL(item, window.location.href);
349
- return {
350
- name: url.pathname,
351
- urls: [item],
352
- type: url.pathname.split('.').pop() || 'js',
353
- };
354
- } else if (Array.isArray(item)) {
355
- if (!item.length) {
356
- return;
357
- }
358
- const url = new URL(item[0], window.location.href);
359
- return {
360
- name: url.pathname,
361
- urls: item,
362
- type: url.pathname.split('.').pop() || 'js',
363
- };
364
- } else {
365
- return item;
366
- }
367
- }).filter(Boolean);
368
-
369
- // 1. 获取全局配置
370
- const {timeout: globalTimeout} = getGlobalConfig();
371
-
372
- // 2. 预检测所有循环依赖(防止无限递归)
373
- checkAllCycles(configList);
374
-
375
- // 3. 初始化缓存(存储已加载资源结果,避免重复加载)
376
- const loadedMap = new Map();
377
-
378
- // 4. 按配置定义的顺序,并行加载同层级无依赖资源(保证依赖先加载,结果保留原始顺序)
379
- const rawOrderPromises = configList.map(async function(config) {
380
- return await loadResourceWithDeps(config.name, configList, globalTimeout, loadedMap);
381
- });
382
-
383
- // 5. 等待所有资源加载完成,返回原始配置顺序的结果
384
- return Promise.all(rawOrderPromises).then(function (result) {
385
- if (result.find(item => item.error)) {
386
- return Promise.reject(result);
387
- }
388
- return result;
389
- });
337
+ return ret;
338
+ } catch (error) {
339
+ errors.push({ url, error });
340
+ }
390
341
  }
391
342
 
392
- resourcePreloader.registerLoader = registerLoader;
393
- resourcePreloader.setGlobalConfig = setGlobalConfig;
343
+ // 所有url都加载失败,抛出最后一个错误
344
+ console.warn(`所有${name}资源加载错误信息`, errors);
345
+ throw new Error(`所有${name}资源加载失败,错误内容看上面`);
346
+ }
347
+
348
+ /**
349
+ * 核心加载调度方法(最终结果保持配置定义顺序)
350
+ * @param {Array<ResourceConfig>} configList - 输入配置数组
351
+ * @returns {Promise<ResourceLoadResult[]>} 按配置定义顺序的加载结果数组
352
+ */
353
+ async function resourcePreloader(configList) {
354
+ if (!Array.isArray(configList) || configList.length === 0) {
355
+ throw new Error("配置数组必须是非空数组");
356
+ }
394
357
 
395
- return resourcePreloader;
358
+ // 将 string[]|string 形式处理成 { name, urls, type } 形式 同时处理 urls:string 为 urls:[string]
359
+ /** @type {Array<FullResourceConfig>} */
360
+ const configs = configList
361
+ .map(function(item) {
362
+ if (typeof item === "string") {
363
+ const url = new URL(item, window.location.href);
364
+ return {
365
+ name: url.pathname,
366
+ urls: [item],
367
+ type: url.pathname.split(".").pop() || "js",
368
+ };
369
+ } else if (Array.isArray(item)) {
370
+ if (!item.length) {
371
+ return;
372
+ }
373
+ const url = new URL(item[0], window.location.href);
374
+ return {
375
+ name: url.pathname,
376
+ urls: item,
377
+ type: url.pathname.split(".").pop() || "js",
378
+ };
379
+ } else {
380
+ if (typeof item.urls === "string") {
381
+ item.urls = [item.urls];
382
+ }
383
+ return item;
384
+ }
385
+ })
386
+ .filter(Boolean);
387
+
388
+ // 1. 获取全局配置
389
+ const { timeout: globalTimeout } = getGlobalConfig();
390
+
391
+ // 2. 预检测所有循环依赖(防止无限递归)
392
+ checkDependencies(configs);
393
+
394
+ // 3. 初始化缓存(存储已加载资源结果,避免重复加载)
395
+ const loadedMap = new Map();
396
+
397
+ // 4. 按配置定义的顺序,并行加载同层级无依赖资源(保证依赖先加载,结果保留原始顺序)
398
+ const rawOrderPromises = configs.map(async function (config) {
399
+ return await loadResourceWithDeps(
400
+ config.name,
401
+ configs,
402
+ globalTimeout,
403
+ loadedMap,
404
+ );
405
+ });
406
+
407
+ // 5. 等待所有资源加载完成,返回原始配置顺序的结果
408
+ return Promise.all(rawOrderPromises).then(function (result) {
409
+ if (result.find((item) => item.error)) {
410
+ return Promise.reject(result);
411
+ }
412
+ return result;
413
+ });
414
+ }
415
+
416
+ resourcePreloader.registerLoader = registerLoader;
417
+ resourcePreloader.setGlobalConfig = setGlobalConfig;
418
+
419
+ return resourcePreloader;
396
420
 
397
421
  }));
398
422
  //# sourceMappingURL=resource-preloader.umd.js.map