zoukankan      html  css  js  c++  java
  • 76Byte让你的JQuery更快

    原文链接:http://james.padolsey.com/javascript/76-bytes-for-faster-jquery/

    When jQuery fires a callback function, whether it is an event handler, an each iterator, or a filter function, it will normally give you a DOM element as the function’s context, accessible via the this keyword. It’s common practice to subsequently wrap this in jQuery(...) resulting in a newly constructed jQuery instance.
    -----------------------------------------
    当jQuery触发一个回调函数时,无论这个函数是一个事件句柄,或者是一个each迭代,再或者是一个过滤器函数,一般情况下它都会把一个Dom元素对象作为函数的上下文,并通过this关键字来获取到它。随后更普遍的做法就是用jQuery(...)来包装this以获得一个jQuery结构的实例。
    -----------------------------------------
    This is no fault of jQuery’s but this practice of redundant “wrapping” generally sucks.

    -----------------------------------------
    这种做法没有错,但是这种“包装”的做法通常显得比较多余而且差劲
    -----------------------------------------
    I “tweeted” a while ago, complaining of this:

    Constructing a new jq obj on each iteration just to access some text seems wrong. jQuery(‘a’).map(function(){ return $(this).text(); });

    -----------------------------------------------

    之前我在我的推上曾经抱怨过:

            在一个each迭代起中构造一个jq对象,确仅仅是为了获得一些文本值,这种做法像是错误的。

    ------------------------------------------------      

    1 jQuery(‘a’).map(function(){ return $(this).text(); });

    ------------------------------------------------
    Paul Irish suggested that I use jQuery.text instead of jQuery.fn.text, meaning that I wouldn’t have to bother with constructing a new jQuery object every single time my function was called. This was a good suggestion but unfortunately not all of jQuery’s methods have corresponding single-node functions, and it would mean not being able to chain methods.
    ------------------------------------------------
    Paul Irish 建议我使用jQuery.text()来代替jQuery.fn.text() ,这意味着我不必每次在函数调用时都去构造一个新的jQuery 对象。这个建议不错但是并非所有的jQuery方法都符合单节点函数(single-node functions),
    而且这意味着将不能够使用链式方法(chain methods)。
    ------------------------------------------------
    This is a growing problem, and is only worsened by developers’ insistence on constructing multiple jQuery objects with the same  element! -

     1 jQuery('a').click(function(){
     2  
     3     if (jQuery(this).attr('href') === 'blah') {
     4         jQuery(this).next('.whatever').slideToggle();
     5     }
     6  
     7     jQuery(this).fadeTo('slow', 0.4);
     8  
     9     return false;
    10  
    11 });

    ------------------------------------------
    This的问题越来越突出,而那些坚持使用同一个元素构造多个jQuery object的开发者显得更糟糕。

     1 jQuery('a').click(function(){
     2  
     3     if (jQuery(this).attr('href') === 'blah') {
     4         jQuery(this).next('.whatever').slideToggle();
     5     }
     6  
     7     jQuery(this).fadeTo('slow', 0.4);
     8  
     9     return false;
    10  
    11 });

    ------------------------------------------
    Eew! Not only are there multiple pointless constructors, but Mr. Uber Cool jQuery Developer isn’t accustomed to the DOM, so has  absolutely no idea that, in most situations, this.href would suffice for getting the href property value.

    This kind of misuse has been discussed in step #3 here: http://encosia.com/2010/03/30/5-steps-toward-jquery-mastery/.

    ---------------------------------------------------------

    Eew! 不仅仅是有多个无用的构造器,而且Mr. Uber Cool jQuery Developer也不习惯dom,在毫无办法时,大多数情况下,this.href就能够满足我们获取元素的href属性值。This的滥用用法在这里被讨论过: http://encosia.com/2010/03/30/5-steps-toward-jquery-mastery/
    ---------------------------------------------------------
    The real problem remains that there are three jQuery objects being constructed, — I feel that it is a library’s obligation to protect  against misuse like this. Even if you’re only constructing one jQuery object in a callback it’s still somewhat pointless, in that you’re only doing so to call a couple of methods…
    -----------------------------------------------------------
    实际情况是我们仍旧构造了三个jq对象,我感觉防止像误用this这是js库的责任,即便如此,如果你在回调中仅仅只构造了一个jq对象仍旧有点无用,因为你只是想调用一组方法而已。
    -----------------------------------------------------------
    In light of my concerns I thought it would make sense to experiment with some ways to alleviate this troublesome situation. In the end, I landed on something so dead-simple that I feel silly even shining a spotlight on it:
    -----------------------------
    从我的观点来看,我认为通过采用一些方法减少这种麻烦是可以的,最后 ,关于这点我贴上一些简单至极却非常有效的代码
    -----------------------------

    jQuery.single=function(a){return function(b){a[0]=b;return a}}(jQuery([1]));

    76 characters. Here’s the readable version:

    -----------------------------
    76字节,这个是通读版本
    -----------------------------

     1 jQuery.single = (function(o){
     2  
     3     var collection = jQuery([1]); // 创建了一个jquery对象,并让他的dom collection的length === 1
     4  
     5     return function(element) {
     6  
     7         // Give collection the element:
     8         collection[0] = element; //替换collection的第一个元素
     9  
    10         // Return the collection:
    11         return collection; //返回替换后的jquery对象
    12  
    13     };
    14  
    15 }());

    A single jQuery object is being created and is then used for every single call to jQuery.single — so only one jQuery object is ever being created. If you think about it, we tend to wrap elements in jQuery(...) (i.e. in a jQuery instance) so that we can have access to jQuery’s methods. Very rarely do we mutate the object itself — even when you call parent() or children(), the jQuery object  itself isn’t being changed — a new object is being returned. It’s this non-mutability which makes this solution viable.

    --------------------------------------

    使用jQuery.single()就可以保证只有一个jquery对象被创建。
    如果仔细想想,我们趋向于用jQuery()包装元素以便我们可以使用jq对象的方法。
    很罕见的我们改变了对象本身,即便当你调用parent()或者children()时,
    jq对象本身也不会被改变,因为已经返回了一个新的对象。 这是this的不变性让这个方案可行。

    --------------------------------------
    Obviously, you can’t use it in exactly the same was as jQuery(); jQuery.single will only work when you pass a single DOM element. Here’s an example of its usage:

    很明显,这样不能够和jQuery()一模一样;jQuery.single只用在你传递一个dom元素的情况下,
    以下是用法的列子:
    -------------------------------------

    1 jQuery('a').click(function(){
    2  
    3     var html = jQuery.single(this).next().html(); // Method chaining works!
    4  
    5     alert(html);
    6  
    7     // etc. etc.
    8  
    9 });

    Also, you can’t cache it and save it for later as you normally would… well, actually, you can — but the object will change when you next call jQuery.single, so be careful! And please note that this is only meant to be used in situations where you have a DOM element that requires immediate wrapping.

    事实上你可以像平常一样缓存和保存它,但是这个对象当你再次调用jQuerysingle之后就会改变,所以要小心使用。
    请注意:这个仅仅用于有个dom元素需要临时打包一下。

    You might be thinking that we could do away with this trickery by simply remembering to “cache” our jQuery objects, like so (using the example from before):

    你也许会认为我们也可以用简单的对象把this储存起来,就想下边这样:

    jQuery('a').click(function(){
     
        var me = jQuery(this);
     
        if (me.attr('href') === 'blah') {
            me.next('.whatever').slideToggle();
        }
     
        me.fadeTo('slow', 0.4);
     
        return false;
     
    });

    This is a good practice, but is still not quite as speedy as jQuery.single. I absolutely recommend making up your own mind by carrying out your own tests, but having tested jQuery.single() myself I can tell you that it performs better.

    这样的做法不错,但是仍旧没有jQuery.single快。我更推荐你去测试一下,但是我可以告诉你在我测试jQuery.single()之后,它表现的更好一些

    You can make it even faster by assigning jQuery.single to a (closely-scoped) variable:

    你可以为jQuery.single分配一个变量来让它更快

    var $_ = jQuery.single;
    // Use $_(this) ...

    这个是在Javascript Design Pattern 徐涛翻译版本中推荐的一篇文章,看了一下 ,个人英语也一般,有些地方不会翻,大体意思上估计差不多了,

    第一次发文,有什么地方不好的请见谅。

  • 相关阅读:
    python 04 list增删改查 迷途小书童
    xhtml+css符合标准的WEB设计
    在Ubuntu16.0.4安装hipcaffe
    简单使用OpenSSL生成密钥
    Ubuntu 16.04 集成安装Apache+PHP+Kerberos+LDAP+phpLDAPadmin
    Ubuntu 安装mysql & 自定义数据存储目录
    TestLink+Jenkins在Ubuntu16.04搭建集成测试环境
    Rancher 2.1平台搭建及使用
    JavaFX_homework1_pane
    linux 命令1 转
  • 原文地址:https://www.cnblogs.com/netlaw/p/3303567.html
Copyright © 2011-2022 走看看