JS懒加载模块封装

通过简短的代码讲述ES模块系统的活用

lazy.js

js 复制代码
/**
 * 懒加载模块
 * @template T
 * @param {()=>Promise<{ default: T }} declare 声明模块
 * @param {(module:T)=>void} customInit 自定义初始化函数,此函数会在执行exports时被调用一次
 */
export function lazyimport(declare, customInit) {
    return {
        wait: declare,
        /**模块实例,执行过exports后,此项才会有值
         * @type {T}*/
        instance: null,
        /**模块初始化
         * @type {()=>Promise<T>} */
        exports: async function () {
            if (!this.instance) {
                this.instance = (await this.wait()).default;
                if (customInit) {
                    customInit(this.instance);
                } else if (this.instance.init) {
                    this.instance.init();
                }
            }
            return this.instance;
        }
    }
}

用法举例

myModule.js

js 复制代码
function helloWord(){
	console.log('Crazy Thursday')
}
export default {
	helloWord
}

app.js

js 复制代码
import { lazyimport } from './lazy.js';
const myModule=lazyimport(()=>import('./myModule.js'));
async function callMyModule(){
	await myModule.exports();
	myModule.instance.helloWord();
}
//在合适的时机调用callMyModule
相关推荐
2013编程爱好者9 小时前
Vue工程结构分析
前端·javascript·vue.js·typescript·前端框架
小满zs10 小时前
Next.js第十一章(渲染基础概念)
前端
不羁的fang少年11 小时前
前端常见问题(vue,css,html,js等)
前端·javascript·css
change_fate11 小时前
el-menu折叠后文字下移
前端·javascript·vue.js
yivifu11 小时前
CSS Grid 布局详解(2025最新标准)
前端·css
o***Z44812 小时前
前端性能优化案例
前端
张拭心12 小时前
前端没有实际的必要了?结合今年工作内容,谈谈我的看法
前端·ai编程
姜太小白12 小时前
【前端】CSS媒体查询响应式设计详解:@media (max-width: 600px) {……}
前端·css·媒体
weixin_4111918413 小时前
flutter中WebView的使用及JavaScript桥接的问题记录
javascript·flutter
HIT_Weston13 小时前
39、【Ubuntu】【远程开发】拉出内网 Web 服务:构建静态网页(二)
linux·前端·ubuntu