Skip to content

Commit 41f3f31

Browse files
author
Pablo Largo Mohedano
committed
Reimplementation of requestAnimationFrame
1 parent 4f76cda commit 41f3f31

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

parallax.js

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,35 @@
55
*/
66

77
;(function ( $, window, document, undefined ) {
8+
9+
// Polyfill for requestAnimationFrame
10+
// via: https://gist.github.com/paulirish/1579671
11+
12+
(function() {
13+
var lastTime = 0;
14+
var vendors = ['ms', 'moz', 'webkit', 'o'];
15+
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
16+
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
17+
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
18+
}
19+
20+
if (!window.requestAnimationFrame)
21+
window.requestAnimationFrame = function(callback) {
22+
var currTime = new Date().getTime();
23+
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
24+
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
25+
timeToCall);
26+
lastTime = currTime + timeToCall;
27+
return id;
28+
};
29+
30+
if (!window.cancelAnimationFrame)
31+
window.cancelAnimationFrame = function(id) {
32+
clearTimeout(id);
33+
};
34+
}());
35+
36+
837
// Parallax Constructor
938

1039
function Parallax(element, options) {
@@ -273,6 +302,20 @@
273302
loadScrollPosition();
274303

275304
this.isReady = true;
305+
306+
var lastPosition = -1;
307+
308+
function frameLoop() {
309+
if (lastPosition == window.pageYOffset) { // Avoid overcalculations
310+
window.requestAnimationFrame(frameLoop);
311+
return false;
312+
} else lastPosition = window.pageYOffset;
313+
314+
self.render();
315+
window.requestAnimationFrame(frameLoop);
316+
}
317+
318+
frameLoop();
276319
},
277320

278321
configure: function(options) {
@@ -295,7 +338,6 @@
295338

296339
requestRender: function() {
297340
var self = this;
298-
299341
self.render();
300342
self.isBusy = false;
301343
},

0 commit comments

Comments
 (0)