jquery的加载运行环境代码分析
程序员文章站
2022-11-08 12:14:03
jquery的加载运行环境
开发环境下jquery3.3.1的代码结构如下所示:
( function( global, factory ) {
"use strict&qu...
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对象上