I speed up my JavaScript animations of the color of each letter in lines of text by:
- using '
IntersectionObserver
' to only run the animations when the text is visible - coloring the elements for the letters in steps with delays in-between. (I also create and get references to these elements in steps)
- sometimes coloring whole lines rather than each letter
- sometimes just coloring lines that are 'above the fold'
- only slowly changing the colors of the letters (about every 20 seconds)
- sometimes not having a '
transition
' for the color changes - delaying the start of the coloring until a few seconds after the page loads
- making the page load quicker by making the page small by putting the JavaScript in separate files. I create '
script
' elements in JavaScript and set their 'src
'. I use 'load
' events to create dependencies between the scripts - not coloring the text on mobiles and tablets. I look at the 'user agent string' and use 'media queries'
- having a separate page for mobiles with no coloring of text. (Google does not recommend this)
I color the letters by adding 'spans
' around each letter and then getting references to each 'span
'. I add a CSS class to each 'span
' and add a stylesheet with the color 'transition
' using JavaScript. The result looks like a rainbow passing through the letters.
There is some sample code at: 'codepen.io/Bert-Beckwith/pen/eYobEKq'
Unfortunately, coloring each letter with JavaScript is very slow. And all the 'spans
' and 'transitions
' make things worse.
But I did not speed up the coloring of letters of text in my JavaScript game. I do not notice the performance problems when playing my game.
A better way might be to have one 'keyframe
' for the rainbow colors and different negative 'animation-delays
' for each letter. The 'animation-delays
' could be set with 'nth-child
'. There is some sample code for this at:
'codepen.io/Bert-Beckwith/pen/ZENYmmo'
The constant coloring of the letters still makes this slow. I would have to create the CSS in JavaScript to allow for animations of a random duration.