From 791d61168ec2772e566a46ec89e081ae895a5af8 Mon Sep 17 00:00:00 2001 From: Michael Cordingley Date: Mon, 2 Dec 2013 13:44:01 -0500 Subject: [PATCH] Fix Image Removal `[].slice.call(foo)` returns an array that is a copy of the array-like `foo`, so when you splice it in this code, you're splicing (and then throwing away) a copy of store. I have edited the code to go ahead and slice the nodeList straight off (which saves cycles _and_ code) and then do the splicing on that directly, so your elements actually do get removed. Also, every time you splice an element out, all of the elements in the array after it get renumbered, so the next iteration ends up skipping an element. An easy remedy to this is to run the loop in reverse, so only previously-iterated elements get renumbered. This also removes the need to check indexOf, as the element in question will never be out of bounds. --- src/echo.js | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/echo.js b/src/echo.js index 5cae710..a3bd0b3 100644 --- a/src/echo.js +++ b/src/echo.js @@ -10,19 +10,16 @@ window.Echo = (function (window, document, undefined) { }; var _pollImages = function () { - for (var i = 0; i < store.length; i++) { - var self = store[i]; - if (_inView(self)) { - self.src = self.getAttribute('data-echo'); - if ([].indexOf && [].slice.call(store).indexOf(self) !== -1) { - [].slice.call(store).splice(i, 1); - } + for (var i = store.length; i--; ) { + if (_inView(store[i])) { + store[i].src = store[i].getAttribute('data-echo'); + store.splice(i, 1); } } }; var init = function () { - store = document.querySelectorAll('[data-echo]'); + store = Array.prototype.slice.call(document.querySelectorAll('[data-echo]')); _pollImages(); window.onscroll = _pollImages; };