🛠️ Front-end Performance: Optimizing a Marquee-style effect using CSS Animation and JavaScript
Channel: Scott Schiller
Date: 2021-07-28

I finally got to refactoring some 7-year-old code that was moving text right-to-left, using a transform style set by JavaScript in an animation loop.

This is one of a round of pending tweaks and improvements; the current version of the game is at http://schillmania.com/armor-alley

I also have a live demo of just the marquee, source code and so on, here. You are welcome to use and modify it as you see fit.
http://schillmania.com/css-marquee-demo/

This by itself might not be so bad, but the marquee has over 100 messages, taking up over 100,000 pixels of width! That's a pretty huge element, and potentially a lot of work for browsers to render.

I finally got to improving the marquee feature, reducing so that only two messages are ever in the DOM at one time. More like 1024 pixels wide, instead of 100,000!

A CSS animation moves the elements from right to left, and the `onanimationcomplete()` event determines when to display the next message.

When the event fires, the leftmost tip has scrolled out of view - and so it can be placed off-screen at the right and updated with new text, recycling of sorts, where it will scroll back into view.

This has turned out to work quite reliably.
I do have to clone and replace nodes to ensure that CSS animations restart, and I'm using an independent node for the `onanimationcomplete()` event; this could probably be improved with testing, to use one of the actual messages being rendered.

I apologize for showing a bunch of code on one screen, at one point - it may not be very legible on smaller screens. I may try to show smaller blocks at a time, using a larger font size in future! 😅