首页 > 解决方案 > 操作 jQuery 得到错误:“jQuery 需要一个窗口和一个文档”

问题描述

如果有人浏览了 jQuery 的未压缩版本,可能会遇到如下情况:

if ( typeof module === "object" && typeof module.exports === "object" ) {

        // 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 );
            };
    } else {
        factory( global );
    }

注意throw new Error()部分。如果我没记错的话,它只会在不存在窗口和文档的情况下引发错误。我知道像 Node.js 这样的东西可能会触发这个错误,但是普通的 HTML、CSS 和 JS 网页可以以任何方式触发这个错误吗?

标签: javascriptjquery

解决方案


  1. Node.js 不会在这里抛出错误,因为它包含一个内部带有“文档”的全局对象;您可以将 jquery 与 Node.js 一起使用。

  2. 最好使用CherrioJS,它专门设计为“类似于 jQuery,但用于服务器。

  3. 尝试将 jQuery 与“ ElectronJS ”或“ Headless Chrome ”一起使用是会引发此错误的示例。


推荐阅读