jQuery optimization selector

后端 未结 4 1636
难免孤独
难免孤独 2021-02-06 08:47

I was wondering the other day when typing you selectors in jQuery would it make a difference in performance if you specify your selectors very specific or very loosely.

4条回答
  •  没有蜡笔的小新
    2021-02-06 09:33

    I would go for:

    $('.someElement', '#myId')
    

    Since getElementById is the fastest selector operation, you are first filtering your content and then searching for the class. Also the fewer the selectors the faster the selections will be (depends if using descendant or child selectors - check comments!) . Test based on @Felix test case.

    Edit: so to enhance this answer. Based on the jQuery documentation:

    By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function.

    So when you provide a second parameter (a context), jQuery will search for that element first and then search within it, so it would be translated from:

    $('.someElement', '#myId')
    

    To:

    $('#myId').find('.someElement')
    

    Now the trick is, trying to find the closest container of your element that actually holds an ID and put it as context, since ID selection is the fastest. Now you would say, why not then using the second already translated one, by I wouldn't actually care that much since the first is cleaner and it's not much slower:

                        $('.someElement', '#myId')                  $('#myId').find('.someElement')
    Chrome 8.0.552              36,527                                      37,400
    Firefox 3.6.13              17,632                                      19,155
    

提交回复
热议问题