Is it better to use jQuery fadeIn or CSS3 animations?

一世执手 提交于 2019-12-18 19:17:16

问题


I am creating a simple gallery using some PHP and JavaScript and am trying to do a fade transition between images. Then I wondered if there is a performance difference between using a CSS animation, e.g.:

@-webkit-keyframes fadeIn {
0%   { opacity: 0; }
100% { opacity: 1; }
}

and a jQuery fadeIn.

I would like to use the callback from the fadeIn but I also can just use a timer with the CSS I guess.

Are either of these likely to work better with large images? I can't see a difference, but wondered if it might affect slower computers.


回答1:


How about one with a fallback to the other? Use CSS3 transitions where possible, and use a feature detection library such as Modernizr to determine if the user's browser is capable of CSS3 transitions.

If AND ONLY IF the user's browser does not support native animations, only then should you use jQuery.

Native animations are GPU accelerated, resulting in less constraint on the CPU, and much smoother animations. Also, IT DOESN'T REQUIRE JAVASCRIPT nor does it take extra requests to pull off.




回答2:


Well, I think using CSS animation is a lot better when there is a supported browser and you should use jQuery only as a backup for unsupported browsers. As thoroughly explained on http://dev.opera.com/articles/view/css3-vs-jquery-animations, they conducted test of animating 300 divs at the same time with both CSS and jQuery, and noticed a huge difference between the performance statistics.

Statistics using CSS the animation were:

    - Number of actions performed to finish the animation: 100
    - Time taken to finish executing the animation: 2.9 seconds
    - Memory consumed at the end of the animation: 1.5 MB

and Statistics using jQuery were:

    - Number of actions performed to finish the animation: 2119
    - Time taken to finish executing the animation: 5 seconds
    - Memory consumed at the end of the animation: 6 MB

So, as you can see, there is a great difference between the performance. This is because the browser's CSS processor is written in C++ and native code executes very fast whereas jQuery (JavaScript) is an interpreted language and the browser can't predict JavaScript ahead in time very well, in terms of what event will occur next, which restricts browsers to optimize it for performance. I hope that answers your question.



来源:https://stackoverflow.com/questions/10863000/is-it-better-to-use-jquery-fadein-or-css3-animations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!