1

So for something like this:

Jquery:

$(document).ready(function(){
    var container = $('.rotate_container');
    var images = container.find('img');
    container.everyTime(10, function (){
        images.each(function() {
            container.animate({scrollTop: $(this).offset().top - 165}, 2000).delay(1000);
        });
    });
});

What's the point of making the variables "container" and "images"? If they're each only used once, how does that help anything at all?

thanks.

android.nick
  • 11,069
  • 23
  • 77
  • 112

3 Answers3

5

If you, for sure, only access an element once in your code, it does not make sense to cache it of course.

The reason for caching DOM elements is that it's awful expensive to access them.

Crossing the bridge between ECMAland and DOMland is the most expensive part. You really can compare it with a bridge, each time you cross it you have to pay a toll. So it makes sense to keep the stuff in ECMAland for which you already payed a toll. Do not cross the bridge each time you need it.

And in this picture you'll notice that it does not matter, if you only cross the bridge once.

jAndy
  • 231,737
  • 57
  • 305
  • 359
  • on one hand, it may take just a little more memory to store the reference to that DOM element, on the other hand, references like this should easily get optimized by the javascript engine, so it will optimize for memory – Quamis Jul 15 '10 at 11:14
0

you could replace images.each with container.find('img').each, but container would then be referred to 3 times (.everytime, .find('img') and .animate).

Emyr
  • 2,351
  • 18
  • 38
0

Those variables essentially fix the values for each timed occurrence. If you think about it, the images could change, markup could be modified, etc. This fixes the DOM element set for the subsequent code. Whether or not is appropriate depends on the application.

cletus
  • 616,129
  • 168
  • 910
  • 942