I’ve been trying to get a working ‘random background on refresh’ on my Tumblr theme. For those that don’t know, Tumblr themes are made up of HTML with embedded CSS and JavaScript.
Right now , I’m using this script:
<script type="text/javascript">
var bg1 = 'http://i.imgur.com/image1.jpg';
var bg2 = 'http://i.imgur.com/image2.jpg';
var bg3 = 'http://i.imgur.com/image3.jpg';
var bg4 = 'http://i.imgur.com/image4.jpg';
var bg5 = 'http://i.imgur.com/image5.jpg';
var randBG=[bg1,bg2,bg3,bg4,bg5];
window.onload=function() {
num=Math.floor(Math.random()*randBG.length);
document.body.style.background='url('+randBG[num]+') no-repeat center center fixed';
</script>
It works, but it causes screen flicker and nullifies my “background-size:cover” property. I’ve tried image preloading, with no success. Tumblr doesn’t support php, and I don’t have a way of hosting a php file to link to.
So, two things. How can I randomize backgrounds on refresh without screen flicker, and, in the process, maintain the following CSS properties?
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
First of all, the flickering is depending on the pre-fetch and the size of the background image. So if the background image is HUGE it’s not going to be ready at the same time as the document. Secondly, calling this on
loadevent means you’re waiting until everything is loaded on the screen before loading the background and therefore, you’re upping the delay. Thirdly, like I said in my comment, you’re blowing away yourbackground-sizewithin your Javascript so you need to do it differently.Here’s what I did.
CSS Snippet
Javascript
Note: These background images are actually huge and I don’t recommend using something that big. Keep them compressed and small so they load faster.
I used jQuery since it has the ability to run something as soon as the
$(document).readyevent fires, which means it fires as soon as the document is ready in the background. I also wait until the image is actually loaded for use and only then do I back it the background image. I don’t believe you’ll be able to completely eliminate the flickering, but I think this will help.