HTML DOM Drawing Transaction in Javascript?

Is there a way to encapsulate multiple DOM transactions in a transaction so that the content doesn't β€œflicker”? Something like that:

window.stopDrawing(); // start transaction $("#news").append("<div>a new news item</div>"); // ... do something more $("#news").css("top", "-150px"); window.startDrawing(); // stop transaction 
+8
javascript drawing
source share
2 answers

Each time you need to update a large set of elements, just set up the function, including all operations, call mozRequestAnimationFrame (or webkitRequestAnimationFrame), only after your function is finished completely, it will display your changes on the screen.

More: https://developer.mozilla.org/en/DOM/window.mozRequestAnimationFrame

+5
source share

I believe that browsers redraw a document only when the script returns to an even loop, so it will not do anything until the end of your script.

In any case, some operations may cause the browser to perform some expensive operations, such as rearranging the sizes of elements in a document (for example, when retrieving the sizes of an element after performing some DOM operations). Thus, you should do DOM manipulations outside the document as much as possible.

If you have a lot of manipulations with some elements, it may be cheaper to remove it from the document tree, perform your manipulations and add it to the tree again.

+2
source share

All Articles