I want to make it lightweight (fastest, best performance) as it possible for browser, but I have no idea - I haven't huge knowledge about JavaScript.
That code run parallax effect on my web page. I have three parallax containers, which are different position background image. Script call on scroll event and when some container exist it's making it parallax-y. The first container ('.parallax-top'
) exists always and hasn't any offset of image - it is always top-positioned. Second and third have offsets (1700 and 1400).
My page have a lot of content, scripts, images and I want to make all of them lightweight as it is possible.
if ($(window).width() > 1200) {
(function() {
var parallaxTop = document.querySelectorAll(".parallax-top");
if ($(".parallax-center").length) {
var parallaxCenter = document.querySelectorAll(".parallax-center");
var centerPosition = $(".parallax-center").position().top;
}
if ($(".parallax-bottom").length) {
var parallaxBottom = document.querySelectorAll(".parallax-bottom");
var bottomPosition = $(".parallax-bottom").position().top;
}
var speed = 0.4;
window.onscroll = function() {
[].slice.call(parallaxTop).forEach(function(el, i) {
var windowYOffset = window.pageYOffset,
elBackgrounPos = "center " + "-" + (windowYOffset * speed) + "px";
el.style.backgroundPosition = elBackgrounPos;
});
if ($(".parallax-center").length)
[].slice.call(parallaxCenter).forEach(function(el, i) {
var windowYOffset = window.pageYOffset,
elBackgrounPos = "center " + "" + ((windowYOffset - centerPosition) * speed + 1700) + "px";
el.style.backgroundPosition = elBackgrounPos;
});
if ($(".parallax-bottom").length)
[].slice.call(parallaxBottom).forEach(function(el, i) {
var windowYOffset = window.pageYOffset,
elBackgrounPos = "center " + "" + ((windowYOffset - bottomPosition) * speed + 1400) + "px";
el.style.backgroundPosition = elBackgrounPos;
});
};
})();
}