一场景,定制个人离线APP,纯html打造,没后端
「没钱买服务器,手机termux一直开着麻烦」
二 功能,让应用启动更迅速。当然,只是给一点方向上参考。肯定有更好的算法。
三 代码,两个,一个html和一个config.js 配置文件放一些 日记,句子 ,项目说明等等转js常量的东西
静态路由,按需加载+缓存


// ==========================================================
// 静态路由下的"按需加载 + 缓存"方案
// 2025-11-21
// ==========================================================
一、说明
-
仅当用户第一次进入三级页时,才去拉取 2_10月脚本.js。
-
脚本一旦加载,立即挂到 window._allScripts,后续任何再进入
该页面均直接从 window 上复用,不再读盘、不再下载、不再执行。
- 纯静态页面,零后端改动,零其他页面改动。
二、三步落地
Step-1 删除原来的静态标签
把页面里这一行整行删掉:
<script src="2_10月脚本.js"></script>
Step-2 在同一 HTML 的 <script> 里(推荐放底部)写:
(function(){
const key = '2_10月脚本.js';
if(window._allScripts && window._allScripts[key]) return; // 已缓存直接返回
const s = document.createElement('script');
s.src = key;
s.onload = () => {
window._allScripts = window._allScripts || {};
window._allScripts[key] = true; // 标记已加载
};
document.head.appendChild(s);
})();
Step-3 业务脚本紧跟其后即可,无需等待回调(脚本执行顺序由浏览器保证)。
三、一页看改法
改前:
<script src="2_10月脚本.js"></script>
<script> /* 你的业务逻辑 */ </script>
改后:
<script>
(function(){
const key = '2_10月脚本.js';
if(window._allScripts && window._allScripts[key]) return;
const s = document.createElement('script');
s.src = key;
s.onload = () => {
window._allScripts = window._allScripts || {};
window._allScripts[key] = true;
};
document.head.appendChild(s);
})();
/* 你的业务逻辑 */
</script>
四、可选增强:通用缓存工具
window.ScriptCache = {
has: function (url) {
return window._allScripts && window._allScripts[url];
},
get: function (url) {
return this.has(url) ? window._allScripts[url] : null;
},
set: function (url, data) {
window._allScripts = window._allScripts || {};
window._allScripts[url] = data || true;
},
remove: function (url) {
if(window._allScripts) delete window._allScripts[url];
},
clear: function () {
window._allScripts = {};
},
stats: function () {
return Object.keys(window._allScripts || {}).length;
}
};
五、使用示例
if (!window.ScriptCache.has('2_10月脚本.js')) {
const s = document.createElement('script');
s.src = '2_10月脚本.js';
s.onload = () => window.ScriptCache.set('2_10月脚本.js');
document.head.appendChild(s);
}
六、注意事项
-
若脚本内部依赖 DOM,请确保加载脚本前 DOM 已就绪(可包在 DOMContentLoaded 里)。
-
若存在同名字段冲突,可把 window._allScripts 换成任意全局变量。
-
本方案仅适用于纯静态站点,无构建工具、无路由框架场景。