Performance of jQuery selector with context

后端 未结 6 1414
南方客
南方客 2020-12-01 05:26

I was reading this article by Brandon Aaron here, about how jquery context may help. So i thought of doing a test of my own. So this is what I did.

  1. Created

6条回答
  •  無奈伤痛
    2020-12-01 06:27

    The #ID selector relies on the browser native document.getElementById. It's going to be fast no matter what.

    Try a selector like div.class[attribute=value] with and without a context. For example*, you could select the "Related" question links to the right with this selector:

    // Selects anchor elements with href's beginning with /questions/
    $('a[href^=/questions/]')
    

    But, it's faster to limit how many anchor elements the selector engine has to iterate over, evaluating that relatively expensive text matching:

    $('a[href^=/questions/]', '.related')
    

    * And ignoring the obviously easier .question-hyperlink class on those links, for the sake of discussion.

提交回复
热议问题