1. 程式人生 > >jquery載入執行環境

jquery載入執行環境

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物件上