How to move page elements without causing a redraw?

I'm currently trying to figure out how I can move elements (to an arbitrary position) on a web page without triggering content review (and therefore lacking a budget of 60 frames per second).

My approach was to use transform: translate(...) , since the composition would be executed on the GPU and does not need any repainting of the content. However, when I change the transform property, the element will be redrawn.

I created an example for this case:

 <!DOCTYPE html> <html> <head> <title></title> <style> #moving { transform: translate(0, 0); width: 100px; height: 100px; background-color: red; } </style> <script src="http://code.jquery.com/jquery-2.0.3.js"></script> </head> <body> <div id="moving"></div> <script> setTimeout(function () { $('#moving').css('transform', 'translate(100px, 100px)'); }, 2000); </script> </body> </html> 
+4
source share
2 answers

you can use css keyframes for this

http://jsfiddle.net/9yqWY/

  #moving { animation: move 2s infinite; -webkit-animation: move 2s infinite; width: 100px; position:relative; height: 100px; background-color: red; } @keyframes move { 0 { transform: translate(0); -webkit-transform: translate(0); -moz-transform: translate(0); } 50% { transform: translate(100px); -webkit-transform: translate(100px); -moz-transform: translate(100px); } 100% { transform: translate(0); -webkit-transform: translate(0); -moz-transform: translate(0); } } @-webkit-keyframes move { 0 { transform: translate(0); -webkit-transform: translate(0); -moz-transform: translate(0); } 50% { transform: translate(100px); -webkit-transform: translate(100px); -moz-transform: translate(100px); } 100% { transform: translate(0); -webkit-transform: translate(0); -moz-transform: translate(0); } } 
+1
source

Repainting is not evil. This is a necessary operation for updating the image on the display. Modern browsers are pretty smart to recolor the smallest required area. In your example, only 0.18 ms is required to complete the Chrome job.

Developer Tools screenshot shows repaint

As the working element becomes larger, repainting will take longer, but still a reasonable amount of time (in most cases). It can become more expensive if it runs many times in a row (e.g. with JavaScript / jQuery animations).

+1
source

Source: https://habr.com/ru/post/1494228/


All Articles