Beautiful parallax 2019 edition
Parallax technique is not new. Few years ago parallax could end up implemented wrong, with jank. Now it’s 2019, browsers are great enough.
There are plenty of examples in the wild. There are also lots of libraries.
Parallax technique can be done with only CSS or with CSS+JS.
Here, I will show you how parallax is easy to implement with CSS variables and I will flavor it with just a little bit of vanilla JS.
Let’s build it
We need to split images by edges.
I removed man from a middle picture in order to have nicer parallax effect.
Minimal code for parallax
And thats it, thats all we need for beautiful parallax, plus whatever other styling we want for page to look nice.
On every scroll event we will update CSS variable (--y) and that will trigger css transform.
I also added
will-change: transform. It’s a hint for browsers to optimize transform changes.
Improvement №1 - Scroll throttling
Scroll usually fires around same rate as animation, around every 16ms. If we ever stumble upon case where scroll fires at a higher rate, we can add code with requestAnimationFrame to guarantee transform change once in 16ms frame.
Improvement №2 - Stop updating parallax
We don’t need to update parallax when it’s not inside viewport. For this we can use IntersectionObserver 🙌
I didn’t add IntersectionObserver options. By default they are exactly what we want.
Improvement №3 - WebP
We can compress images even more and use WebP format in order to download less data with similar image quality.
Recently released online tool squoosh.app is awesome. Drop an image and select WebP format. We can play around with settings, compare with original and in the end download what we like.
Chrome, Firefox, Opera and Edge supports WebP and every other browser (Safari) will get png. We have to progressively enhance our html with picture tag.
Now we will download ~1.9MB 🎉🎉🎉
We can use responsive images, and deliver high-res images only to bigger screens and smaller images to the smaller screens.
We can use something like this:
Quality of image is not priority on mobile, so now on mobile devices we will pull only ~500KB of images.
Thats all. It’s 2019, creating beautiful parallax has never been easier 😎