What is the impact of performance on using jquery functions?

I posted another question on a very similar topic, but it turned out to be a bit subjective. I can divide the question into two questions, which I will explain below:

In the following code:

<script type="text/javascript">
$(function() 
{
   $("#accordion").accordion();
   $("#datepicker").datepicker();
   $("#button").click(function() 
   {
     runEffect();
     return false;
   });
});
</script>

Question: If I have this code called on 1000 pages, but only 250 pages have a date identifier. Will the browser spend extra time on the other 750 pages trying to parse the date id, or does jQuery have a smart way to solve this situation without affecting performance?

What happens if the code refers to identifiers or classes that do not exist in the html markup of the current page, will this affect performance?

+3
8

, " ", .

, , JS:

$(function() {
  // do lots and lots of stuff
});

Javascript HTML (PHP). , , :

$(".someClass").doStuff();

$("div.someClass").doStuff();

.. Javascript , 95% . ? - , ..

JS:

function activate_accordion() {
  $("#accordion").accordion();
}

, , . : Javascript Javascript, . Javascript , , .

HTML-:

<script type="text/javascript">
$(function() {
  activate_accordion();
}
</script>

Javascript, . , , , /, - .

Javascript 50-100 ( 1-2 ) .

+7

, , .

jQuery , .

, #id getElementById, .

, .

+2

, jquery 'datepicker'.

, ID, , , , , , .

, - . .

, . , , , , .

+2

, :

  • $("#accordion").accordion()
    • :
      • "#accordion"
    • :
      • #accordion, ,

: IMO:

  • .
  • .

2, , , :

$el = $('#myElement');
if ($el.length) {
    $el
        .find("div")
        .each(function () { .. })
        .parents()
    // etc...
}

, , . , :

:

// doing this:
var $f = $('#fakeElement');
if ($f.length) $f.find('div');

// is almost twice as fast as this:
$('#fakeElement').find('div');

// For 10000 iterations, 404ms vs 788ms in my tests
+1

?

10000 .

$('div#datepicker');
// 179ms

$('#datepicker').find('div');
// 65ms

var $dp = $('#datepicker'); if ($dp.length) $dp.find('div');
// 32ms

if (document.getElementById('datepicker')) $('#datepicker').find('div');
// 1ms
+1

jQuery , . , , , , , javascript, .

, , , , SLaks, , , .

0

, , :

if( $('#accordion').length > 0 ){
     // 20 lines of #accordion-dependent code here
}
0

$('body').find("#datapicker")... .

. : >

if($("#datepicker")[0]) {...}

.

0

Source: https://habr.com/ru/post/1719477/


All Articles