I'm trying to write some image transitions in Javascript.
Page is here: http://shineemc.com/trans/
(All code is in a single page, just do a "view source")
I have one part of my code that is seriously slow. I have tried it a few different ways, but it's slow no matter what. I have done some logging, and it seems to be when getting the position of an element the very first time:
2016-02-01 15:54:28.386 (index):72 Setting BG position
2016-02-01 15:54:28.387 (index):83 In Each loop
2016-02-01 15:54:30.029 (index):85 Got div position
2016-02-01 15:54:31.148 (index):87 Set one BG
2016-02-01 15:54:31.148 (index):83 In Each loop
2016-02-01 15:54:31.171 (index):85 Got div position
2016-02-01 15:54:31.172 (index):87 Set one BG
console.log("Setting BG position");
$tiles.each(function() {
console.log("In Each loop");
var pos = $(this).position();
console.log("Got div position");
$(this).css( 'backgroundPosition', -pos.left +'px '+ -pos.top +'px' );
console.log("Set one BG");
});
If you look at the log timestamps, there's a big delay between when it first enters the "each" loop to when it gets the first position for a tile. (~1.7 secs)
I have tried doing this as a for loop, thinking that the "each" was being it's usual slow self, but the behavior carries over.
Using "for" loop:
2016-02-01 16:08:25.473 (index):72 Setting BG position
2016-02-01 16:08:25.474 (index):74 In For loop 1
2016-02-01 16:08:27.147 (index):77 Got div position
2016-02-01 16:08:28.299 (index):79 Set one BG
2016-02-01 16:08:28.300 (index):74 In For loop 2
2016-02-01 16:08:28.320 (index):77 Got div position
2016-02-01 16:08:28.321 (index):79 Set one BG
for (var i = 1; i < num_tiles; i++) {
console.log("In For loop", i);
var curTile = $('#tile'+i);
var pos = curTile.position();
console.log("Got div position");
curTile.css( 'backgroundPosition', -pos.left +'px '+ -pos.top +'px' );
console.log("Set one BG");
}
I have used ID's instead of class selectors, Appended from a long string instead of making jQuery do it 36 times... I'm out of ideas.... What could be slowing this code down, and how can I get it up to speed?
Thanks in advance for any help.