Reputation: 96
I implemented a loading indicator (an animated .svg) with fadeIn and fadeOut to show/hide it on a page which also has an animated canvas, and there is a considerable drop in performance of my canvas while these operations are occurring, even going so far as to crash a certain mobile browser.
I changed it to simply show() and hide() the element, and there is no problem except it doesn't look quite as nice.
Just wondering if anyone else has noticed such performance issues, and if there is perhaps an alternative way to fade my indicator in/out? Thanks!
Upvotes: 0
Views: 1359
Reputation: 91555
JQuery's animation routines are all very "pessimistic" in their implementation. They use timers to explicitly set the opacity in the DOM frame by frame. This causes the browser to force redraws. This is done for historical reasons because CSS transitions didn't always exist and it used to be the only way to achieve these effects.
Now, a more efficient way to let the browser do most of the work using CSS transitions. Rather than letting JQuery do the fading, you simply use it to apply a class. The browser takes care of transitioning between the two states.
Most browsers can accelerate opacity and transform transitions using the GPU.
setTimeout(function() {
$('.fader').addClass('show');
$('.fader').on('click', function() {
$(this).removeClass('show');
});
});
.fader {
width: 200px;
height: 200px;
background: cornflowerblue;
opacity: 0;
transition: opacity 2s linear;
}
.show {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fader">I'll fade in, click me to fade out</div>
In the example above, the setTimeout()
is used to give the DOM a frame to draw up the <div>
with the fader
class with an opacity
of 0
. In the next frame it applies the show
class which sets the opacity
to 1
. Because the transition
is 2 seconds long, it will slowly fade in.
I also added a click event that removes the show
class and it will slowly fade back out.
Upvotes: 2