【问题标题】:How can I reduce jQuery?如何减少 jQuery?
【发布时间】:2010-04-28 23:46:33
【问题描述】:

我在我的网站上只使用了一些基本的 jQuery 函数。
如何删除未使用的 jQuery 代码?
只知道基础知识,我查看了代码,不知道从哪里开始。 如果你能指出我正确的方向,那将不胜感激。

谢谢。

【问题讨论】:

  • 那真的是一个拼写纳粹;)(顺便说一句,这是语法...这不是递归的吗?)
  • 此外,您可以通过破坏代码来缩小生成的 jQuery 库以将其压缩大约 55%(谷歌编译器应用程序)。尽管我确实同意@strelokstrelok - 这是一个非常简单的步骤,因为您页面上的奇怪广告会有更大的文件大小。

标签: jquery


【解决方案1】:

jQuery 本身并不是真正为选择性使用而构建的。它自己的功能之间有很多相互依赖关系,并且源代码的布局并不容易模块化。与 jQuery-UI 等插件的情况不同,jQuery 的核心几乎是接受它或离开它。

如果您只使用过几个简单的函数,您也许可以用纯 JavaScript 重写它们。如果您使用的主要功能是选择器,您可以使用Sizzle,这是 jQuery 本身使用的底层选择器库。否则......不是真的。

【讨论】:

  • 值得指出的是,这种模块化是 jQuery 下一个主要版本的主要目标之一——通过允许开发人员(大致)指定哪些部分来使库更好地缩小规模他们需要的 jQuery 并跳过其余部分。
【解决方案2】:

如果您想进一步减少代码大小,请缩小并 gzip 或放气。请注意,gzip 压缩的代码在执行之前需要解压缩,从而导致延迟。 jQuery 下载页面提供了一个已经缩小和 gzip 压缩的版本。

您可以考虑的另一个选项是使用 CND 托管的 jQuery,即由 Google 或 Microsoft 等第三方组织托管的 jQuery。 Details in the jQuery download page.

【讨论】:

  • 只需将“gzip”替换为“deflate”,我同意。见this
  • 我不知道 deflate 相对于 gzip 的优势。谢谢!
【解决方案3】:

问题是 - 为什么? jQuery 1.4.2 的生产版本只有 24Kb。通过对文件进行适当的缓存控制,它只会被下载一次并被缓存。何必呢?

【讨论】:

  • 昂贵的互联网税,你知道的。
  • Strelokstrelok,虽然绝对正确,但您并没有回答汤米的问题——这既公平又简单。
【解决方案4】:

正如其他人所提到的,您不需要这样做。

如果担心带宽问题,可以reference jQuery from Google's AJAX API,如下:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.js"></script>

要回答这个问题,那将是极其困难的。

正如您所注意到的,jQuery 以非常简洁和高效的方式编写,并且没有容易移除的块。

【讨论】:

    【解决方案5】:

    除了缩小/压缩/CDN 托管 Javascript 的技巧(您应该为任何 Javascript 库执行此操作)之外,请查看Zepto,它旨在成为为移动浏览器设计的更轻薄的 jQuery 替代方案。它不是 jQuery 的直接替代品,但支持所有重要的东西,如选择器、AJAX 操作和实用程序。我写了一篇关于这个主题的简短博文:http://blog.straylightrun.net/2012/10/23/so-you-want-to-use-jquery-in-your-javascriptwidget/

    【讨论】:

      【解决方案6】:

      您可以按照此处的官方 jQuery 存储库中的文档创建自己的版本:https://github.com/jquery/jquery#how-to-build-your-own-jquery,但这涉及使用 Grunt。

      如果您使用的是 Webpack,您可以按照此处的步骤操作:https://gist.github.com/rhaglennydd/abb2d27144e1a595e7c850b0a7611a21

      我认为链接只回答违反了 SO 中的一些规则,所以我给出一个简短的描述。

      1。通过 npm 安装 jQuery

      npm install jquery
      

      2。复制导出的代码

      将代码从node_modules/jquery/src/jquery.js 复制到项目中的文件(例如code/resources/js/jquery

      3。编辑源文件路径

      导入的文件必须是node_modules文件夹中的原始文件。 例如'./core', 可以变成'../../../node_modules/jquery/src/core'

      4。删除不需要的模块

      删除或注释某些模块:确保测试您的代码是否继续工作而不会引发错误。

      5。在 Webpack 配置中添加自定义 jQuery 作为别名

      这将告诉 Webpack 在您的代码或其中一个依赖项中需要 jquery 时使用您的版本。 例如:

      module.exports = {
        resolve: {
          alias: {
            jquery: `${environment.paths.source}/js/jquery-custom/jquery-custom.js`,
          }
        }
      };
      

      最后一句话

      我已经看到,如果我删除了很多模块,大小会减小,但如果你不这样做,它甚至会略微增加:所以如果你需要逐步删除一些代码或者如果你已经使用了,这是一个很好的策略很少的模块,否则你最好坚持原来的或找到一个替代库。

      【讨论】:

        【解决方案7】:

        这是一个老问题,但仍然是相关的话题......

        这是我炮制的(请注意,这只是一个草稿,可以作为起点)

        $ = function () { 
            if ( arguments[0] !== undefined ) {
                stubelement = arguments[0] ;
                if ( typeof stubelement == "string" ) {
                    switch ( true ) {                   
                        case stubelement == 'body' : return document.querySelector(stubelement); break;
                        case stubelement == 'html' : return document.querySelector(stubelement); break;
                        case stubelement.charAt(0) == ',' : if( document.querySelectorAll(stubelement.replace(',','.')).length > 0 ) { return document.querySelectorAll(stubelement.replace(',','.'))[0]; } break;
                        case stubelement.charAt(0) == '.' : if( document.querySelectorAll(stubelement).length > 0 ) { return Array.from(document.querySelectorAll(stubelement)); } break;
                        case stubelement.charAt(0) == '#' : if( document.querySelectorAll(stubelement).length > 0 ) { return document.querySelectorAll(stubelement)[0]; } break;
                        default :   if( document.querySelectorAll(stubelement).length > 0 ) { return document.querySelectorAll(stubelement)[0]; } break;
                    }
                } else { return arguments[0]; }
            } 
            return document.querySelectorAll("#emptyelement")[0];
        }
        
        function stubappento () { if ( (arguments[0] !== undefined) && (arguments[1] !== undefined) ) { $(arguments[1]).append($(arguments[0]).outerhtml()); $(arguments[0]).remove(); } }
        function stubprepento () { if ( (arguments[0] !== undefined) && (arguments[1] !== undefined) ) { $(arguments[1]).prepend($(arguments[0]).outerhtml()); $(arguments[0]).remove(); } }
        
        HTMLElement.prototype.val = function () { if ( arguments[0] !== undefined ) { this.value = arguments[0]; } else { return this.value; } };
        HTMLElement.prototype.html = function () { if ( arguments[0] !== undefined ) { setInnerHTML(this,arguments[0]); } else { return this.innerHTML; } };
        HTMLElement.prototype.append = function () { if ( arguments[0] !== undefined ) { setInnerHTML(this,(this.innerHTML + arguments[0])); } else { setInnerHTML(this,(this.innerHTML + ' ')); } };
        HTMLElement.prototype.prepend = function () { if ( arguments[0] !== undefined ) { setInnerHTML(this,(arguments[0] + this.innerHTML)); } else { setInnerHTML(this,(' ' + this.innerHTML)); } };
        HTMLElement.prototype.outerhtml = function () { if ( arguments[0] !== undefined ) { this.outerHTML = arguments[0]; } else { return this.outerHTML; } };
        
        HTMLElement.prototype.attr = function () { if ( arguments[1] !== undefined ) { this.setAttribute(arguments[0],arguments[1]); } else { return this.getAttribute(arguments[0]); } };
        HTMLElement.prototype.data = function () { return this.getAttribute('data-' + arguments[0]); };
        
        HTMLElement.prototype.css = function () { 
            if ( typeof arguments[0] == 'object' ) { for ([csskey, cssvalue] of Object.entries(arguments[0])) { this.style[csskey] = cssvalue; } } 
            else { if ( arguments[1] !== undefined ) { this.style[arguments[0]] = arguments[1]; } else { return this.currentStyle ? this.currentStyle[name] : window.getComputedStyle ? window.getComputedStyle(this, null).getPropertyValue(arguments[0]) : null; } }
        };
        
        HTMLElement.prototype.remove = function () { this.parentNode.removeChild(this); };
        HTMLElement.prototype.hide = function () { this.style.display = 'none'; };
        HTMLElement.prototype.show = function () { this.style.display = 'inline-block'; };
        HTMLElement.prototype.showblock = function () { this.style.display = 'block'; };
        HTMLElement.prototype.toggle = function () { 
            stubtoggle = this.getAttribute('data-stubtoggle');
            if ( stubtoggle === null ) {
                displa = this.style.display; 
                if ( this.classList.contains("inlineBlock") ) { displa = 'inline-block'; }
                log("null-->>"+displa);
                switch (displa) {
                    case 'block' : displa = 'blocksee'; break;
                    case 'inline-block' : displa = 'inlinesee'; break;
                    case 'none' : displa = 'inlineunsee'; break;
                    default : displa = 'blocksee'; break;
                }
            } else {
                displa = this.data('stubtoggle'); log("set-->>"+displa);
            }
            switch ( displa) { 
                case 'blockunsee' : this.setAttribute('data-stubtoggle','blocksee'); this.showblock(); break;
                case 'blocksee' : this.setAttribute('data-stubtoggle','blockunsee'); this.hide(); break;
                case 'inlineunsee' : this.setAttribute('data-stubtoggle','inlinesee'); this.show(); break;
                case 'inlinesee' : this.setAttribute('data-stubtoggle','inlineunsee'); this.hide(); break;
            }
        };
        
        HTMLElement.prototype.length = function () { return this.innerHTML.length; };
        HTMLElement.prototype.width = function () { return this.getBoundingClientRect().width; };
        HTMLElement.prototype.height = function () { return this.getBoundingClientRect().height; };
            
        HTMLElement.prototype.addClass = function () { this.classList.add(arguments[0]); };
        HTMLElement.prototype.removeClass = function () { this.classList.remove(arguments[0]); };
        
        HTMLElement.prototype.disable = function () { this.disabled = true; };
        HTMLElement.prototype.change = function () { this.dispatchEvent(new Event('change')); };
        HTMLElement.prototype.stubtrigger = function () { this.dispatchEvent(new Event(arguments[0])); };
        HTMLElement.prototype.on = function () { this.addEventListener(arguments[0],arguments[1]); };
        HTMLElement.prototype.off = function () { this.removeEventListener(arguments[0],arguments[1]); };
        
        Array.prototype.count = function () { return this.length; };
        Array.prototype.hide = function () { this.forEach(function(a){a.hide();}); };
        Array.prototype.show = function () { this.forEach(function(a){a.show();}); };
        Array.prototype.remove = function () { this.forEach(function(a){a.remove();}); };
        

        而且用法和jquery真的很像

        $().html();
        $().html("new content");
        $().append("new content");
        $().prepend("new content");
        
        $("#tomove").appendTo("#newid");   ===>>> stubappento(',ap','#message2');
        
        $().val();
        $().val("new val");
        
        $().hide();
        $().show();
        $().remove();                               
        $().toggle();
        

        // 对于 slideToggle 只需添加 style="transition:height 1s;"到所需的 div 或添加是 .css 中的一个类 .transitheight1{transition:height 1s;}

        $().attr("a");
        $().attr("src","new src");
        
        $().each ===>>>     $('.bees').forEach(function(a,b){a.hide();});
        
        $().css
        $().width
        $().height
        
        $().addClass
        $().removeClass
        
        $().on("focus",function(){});
        
        $().oninput() ====>>>>>> onclick="$(this).on('input',function(){});"
        
        $().focus()
        $().change()
        $().click()
        
        $().keyup(function(event) {}); ====>>> window.onkeyup = funcname; —— https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event
        $().keydown(function(event) {}); ====>>> window.onkeydown = funcname; 
        
        $().prop("disabled", true); ====>>>>>> $('#id').disable()
        
        $().length ••••••••••••••••••••••••••>>>>>>      $('#ap4ee')?.length()
        
        $()[0].play(); OR .get[0].play =====>>>> $('#audio').play();
        $()[0].pause(); =====>>>> $('#audio').pause();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-11-09
          • 1970-01-01
          • 1970-01-01
          • 2021-04-25
          • 1970-01-01
          • 2019-10-26
          • 2017-10-04
          相关资源
          最近更新 更多