jquery加载运行环境

本文介绍了jQuery在不同环境下的加载运行方式,包括在nodejs中的CommonJS环境,使用webpack+vue的CommonJS-like环境,以及直接在HTML文件中通过外部脚本引入的情况。在nodejs中,jQuery的module.exports返回函数,浏览器环境中则通过import或外部脚本将其挂载到window对象上。

jquery的加载运行环境

开发环境下jquery3.3.1的代码结构如下所示:

( function( global, factory ) {
    "use strict";
    if ( typeof module === "object" && typeof module.exports === "object" ) {
        console.log(module)
        console.log(module.exports)
        console.log(global)
        console.log(global.document)
        // For CommonJS and CommonJS-like environments where a proper `window`
        // is present, execute the factory and get jQuery.
        // For environments that do not have a `window` with a `document`
        // (such as Node.js), expose a factory as module.exports.
        // This accentuates the need for the creation of a real `window`.
        // e.g. var jQuery = require("jquery")(window);
        // See ticket #14549 for more info.
        module.exports = global.document ?
            factory( global, true ) :
            function( w ) {
                if ( !w.document ) {
                    throw new Error( "jQuery requires a window with a document" );
                }
                return factory( w );
            };

        console.log(module.exports)
    } else {
        console.log(global)
        factory( global );
    }
// Pass this if window is not defined yet
} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { ... });

nodejs环境下(CommonJS )

module是一个对象,window是undefined,module.exports会返回一个函数,当调用$.isFunction等类似的静态方法时都会输出undefined

浏览器环境(CommonJS-like )

这里我是用webpack+vue做的测试demo,webpack来做模块的管理,在vue的单文件组件里import jquery脚本,会通过factory( global, true )返回一个jquery对象

浏览器环境(在html文件里引入)

在html文件里通过外部脚本的方式引入jquery,会通过执行factory( global )将jquery对象挂载到window对象上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值