@lynx-js/web-core
Version:
This is an internal experimental package, do not use
66 lines • 3.46 kB
JavaScript
// Copyright 2023 The Lynx Authors. All rights reserved.
// Licensed under the Apache License Version 2.0 that can be found in the
// LICENSE file in the root directory of this source tree.
export function createChunkLoading(entryTemplateUrl) {
const templateCache = new Map();
const readScript = (sourceURL, templateUrl) => {
if (!templateUrl || templateUrl === '__Card__') {
templateUrl = entryTemplateUrl;
}
const finalSourceURL = templateCache.get(templateUrl)?.[`/${sourceURL}`] ?? sourceURL;
const xhr = new XMLHttpRequest();
xhr.open('GET', finalSourceURL, false);
xhr.send(null);
if (xhr.status === 200) {
return xhr.responseText;
}
throw new Error(`Failed to load ${sourceURL}, status: ${xhr.status}`);
};
const readScriptAsync = async (sourceURL, templateUrl) => {
if (!templateUrl || templateUrl === '__Card__') {
templateUrl = entryTemplateUrl;
}
const finalSourceURL = templateCache.get(templateUrl)?.[`/${sourceURL}`] ?? sourceURL;
return new Promise((resolve, reject) => {
fetch(finalSourceURL).then((response) => {
if (response.ok) {
response.text().then((text) => resolve(text), reject);
}
else {
reject(new Error(`Failed to load ${sourceURL}, status: ${response.status}`));
}
}, reject);
});
};
const createBundleInitReturnObj = (jsContent) => {
const foo = new Function('postMessage', 'module', 'exports', 'lynxCoreInject', 'Card', 'setTimeout', 'setInterval', 'clearInterval', 'clearTimeout', 'NativeModules', 'Component', 'ReactLynx', 'nativeAppId', 'Behavior', 'LynxJSBI', 'lynx',
// BOM API
'window', 'document', 'frames', 'location', 'navigator', 'localStorage', 'history', 'Caches', 'screen', 'alert', 'confirm', 'prompt', 'fetch', 'XMLHttpRequest', 'webkit', 'Reporter', 'print', 'global',
// Lynx API
'requestAnimationFrame', 'cancelAnimationFrame', jsContent);
return {
init(lynxCoreInject) {
const module = { exports: {} };
const tt = lynxCoreInject.tt;
foo(undefined, module, module.exports, lynxCoreInject, tt.Card.bind(tt), tt.setTimeout, tt.setInterval, tt.clearInterval, tt.clearTimeout, tt.NativeModules, tt.Component.bind(tt), tt.ReactLynx, tt.nativeAppId, tt.Behavior, tt.LynxJSBI, tt.lynx,
// BOM API
tt.window, tt.document, tt.frames, tt.location, tt.navigator, tt.localStorage, tt.history, tt.Caches, tt.screen, tt.alert, tt.confirm, tt.prompt, tt.fetch, tt.XMLHttpRequest, tt.webkit, tt.Reporter, tt.print, tt.global, tt.requestAnimationFrame, tt.cancelAnimationFrame);
return module.exports;
},
};
};
return {
readScript,
loadScript: (sourceURL, templateUrl) => {
const jsContent = readScript(sourceURL, templateUrl);
return createBundleInitReturnObj(jsContent);
},
loadScriptAsync: async (sourceURL, callback, templateUrl) => {
readScriptAsync(sourceURL, templateUrl).then((jsContent) => {
callback(null, createBundleInitReturnObj(jsContent));
});
},
templateCache,
};
}
//# sourceMappingURL=createChunkLoading.js.map