1

I wanna prevent the CSS transition on page load and I came out with my own solution.

Because the answer here isn't working for me Stop CSS transition from firing on page load

However, I myself do not understand my own solution although it works...

My solution is to add a preload class with transition: none!important; to the body, then remove this class when the page is fully loaded.

What I don't understand is that this script is before the footer, I guess when the browser reaches this line, the CSS transition is already loaded because I put the CSS file in the header tag.

But why is this code still works?

const body = document.querySelector('body');

body.classList.add('preload');

window.addEventListener('load', function() {
  body.classList.remove('preload');
});
nakar20966
  • 123
  • 9
  • 1
    Could it be that the page and the JS load so fast that your script runs before you can see any animation happening? – Gio Polvara Apr 26 '22 at 17:37
  • @GiorgioPolvara-Gpx This is possible but not quite convincing. We all know the reason why we put the JS file at the very bottom is to let the browser reaches the codes before the script. But now the script is reached before the codes/CSS even it's placed at the bottom and after the CSS file ( in the header tag ) – nakar20966 Apr 26 '22 at 17:44
  • For sure the CSS is running before the JS but is it possible that the animation starts, the JS runs and blocks it and it does it so quickly that you don't see any of the animation happening? BTW, why don't you do the reverse? Don't run the animation unless the `loaded` class is defined and you add the class only on load. – Gio Polvara Apr 29 '22 at 10:42
  • @GiorgioPolvara-Gpx This might be a great solution but not suitable if there are many elements and if there are different transition values. – nakar20966 Apr 29 '22 at 13:03

0 Answers0