In this tutorial you are going to learn how to randomize an Elementor background image set on a container or a section.
I was very careful to code it so that the default background image won't load at all. That way, the performance is optimal, or at least as optimal as can be when dealing with CSS background images.
Here is a demo. Click the reload icon in the top right to see the various background images.
Note that if you are looking for a random background image slideshow, I have a tutorial about that as well.
First, add this Elementor random background image code to your project
You will need to use the Code Snippets plugin, or your child theme functions.php file.
<script> /* Please login to get the code * The code will be for the Elementor Random Background Image (Optimized for Speed) tutorial * Found at this URL https://element.how/elementor-random-background-image/ */ </script>
Here is what it looks like in a Code Snippet:
Don't forget to active your code snippet by clicking on the top right button.
Then, let's setup your container or section
You will want a background image already present there. It's required so that the other settings are set; the background position and size in particular. You will probably want these to "center center" and "cover", respectively.
Then add the class name randomBGImage to your container or section.
Finally, add your images URL as attribute
Now, you will want to add a comma separated list as a data-images attribute.
It needs to be formatted that way:
Note that it is all on the same line! No line breaks. In the Elementor editor, it will wrap:
That's perfectly fine.
Exclude from delay JS
In case you are using WP Rocket, or another optimization plugin with a similar delay JS feature, you will want to add randomBGImage to the exclusion list.
Same goes for styles, in case you are merging them. Exclude randomBGImage from merging.
Merging styles or JS files isn't recommended though. Learn more about this in my setting up WP Rocket tutorial, and learn how to get great performance in my get 90 page speed score on mobile tutorial.
Enjoy your new random background image setup!