Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I avoid JS when possible and use CSS instead? [closed]

I'm looking for best practice answer. Currently I'm trying to add a dropdown menu to the navigation bar of my website. I've found that I could do it using CSS and that I could also do it using JS - Angular. I've read that because with JS malicious things can be programmed some people disable JS. Therefore to keep your websites functionality on more computers it should be programmed in CSS. Is there any merit to this? Should I avoid coding in JS when possible?

like image 493
Vindictive Avatar asked Oct 23 '25 03:10

Vindictive


1 Answers

Here are few important reasons why you should prefer using CSS over JS.

  • CSS animations are much better in performance compared to JS animations. CSS doesn't take as much memory as JS for rendering animations.
  • If your animation depends on the screen width, CSS media queries work like a charm without any lag. But if you have to achieve this using JS, you will have to bind an event to the window size and perform an action on every resize.
  • Javascript animations always have slightly higher overhead than CSS animations because in the end JS animations would be manipulating the CSS styles for animations.

However, like how they say, every advantage has its disadvantage. CSS animations don't give the freedom to perform any animation.

Animating the scale, rotation, and position of an element is incredibly common. In CSS, they're all crammed into one "transform" property, making them impossible to animate in a truly distinct way on a single element. For example, what if you want to animate "rotation" and "scale" independently, with different timings and eases? Maybe an element is continuously pulsing (oscillating scale) and you'd like to rotate it on rollover. That's only possible with JavaScript.

Reference: Myth Busting: CSS Animations vs. JavaScript

If you want the flexibility of JS animations and the speed of CSS animations, you should try GSAP, which is built on JavaScript and is much faster than CSS animations. Here is the performance test comparing CSS animations (using Zepto), jQuery animations and GSAP animations. Not to forget, the results may vary as per the rendering engine.

Conclusion: This is how you can go about it.

Simple animations, CSS achievable: Use CSS

Simple animations, can't achieve with CSS: Use JS

Heavy animations: Use GSAP or craft your animations with requestAnimationFrame.

Here is an amazing performance comparison between CSS animation and JS requestAnimationFrame implementations.

like image 141
atman Avatar answered Oct 25 '25 19:10

atman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!