Unexpected Facts about Refresh Flicker (Tumblr)

I've been attempting to implement a 'random background on refresh' feature for my Tumblr theme. As some may not be aware, Tumblr themes are comprised of HTML alongside embedded CSS and JavaScript.

At the moment, I have been utilizing this particular 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>

The current implementation works as intended, but it results in screen flickering and negates my "background-size:cover" declaration. Various attempts at image preloading have proved unsuccessful. Since Tumblr does not support PHP and I lack an external hosting option for a PHP file, I am limited in potential solutions.

Hence, there are two primary concerns. How do I randomize backgrounds upon refreshing without experiencing screen flicker, while also retaining the following CSS properties?

-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

Answer №1

One key factor contributing to flickering is the pre-fetch process and the size of the background image. If the background image is large, it may not load simultaneously with the document. Additionally, triggering this action on the load event means waiting for all screen elements to load before rendering the background, causing a delay. Furthermore, manipulating the background-size in JavaScript can disrupt the display setup.

My Approach:

CSS Code Snippet

<style>
...
body {
  background: url('') no-repeat center center fixed;
  -moz-background-size: cover;
  background-size: cover;
}
...
</style>

JavaScript Implementation

<script type="text/javascript">
    $(document).ready(function(){
        var bg1 = 'http://i.imgur.com/enkkn.jpg';
        var bg2 = 'http://i.imgur.com/BZBke.jpg';
        var bg3 = 'http://i.imgur.com/QOvQH.jpg';
        var bgs = [bg1, bg2, bg3];
        var num = Math.floor(Math.random() * bgs.length);
        var bg = new Image();
        bg.src = bgs[num];
        $(bg).load(function(){
            document.body.style.backgroundImage = "url(" + this.src + ")";
        });
    });
</script>

Important Note: Opt for optimized, smaller background images to enhance loading speed. jQuery's seamless integration with the $(document).ready event ensures timely execution without disrupting the user interface. Loading images first before setting them as backgrounds can reduce flickering, although complete elimination may be challenging.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting a CSS layout problem: Organizing a webpage layout using CSS that includes an

I am currently facing an issue with arranging a container inline and it seems like there is something missing in my CSS code. After applying float:right, the class "second" does not seem to work as expected. Here's how my container is structured: &l ...

Error: Attempting to access the 'getCroppedCanvas' property of an undefined value in VueJs

I've been exploring the vue-cropperjs library, but every time I execute the code, I encounter error messages: Uncaught TypeError: Cannot read property 'getCroppedCanvas' of undefined Uncaught TypeError: Cannot read property 'replace&ap ...

Detecting Unflushed Requests in Jasmine and AngularJS

I'm encountering some issues passing certain tests after implementing $httpBackend.verifyNoOustandingRequest(). Interestingly, excluding this from my afterEach function allows the tests to pass successfully. However, including it causes all tests to ...

The final element that fractures all its sibling elements positioned absolutely

I am experiencing an issue with a container div that contains 5 absolutely positioned images. When I specify the last image as absolutely positioned, all other images lose their positioning and stack at the top. The container itself is relatively position ...

css apply liquid-like resizing to div element

I'm trying to set the height of the container to automatically adjust if the content overflows, allowing it to flow naturally. This is the code I'm currently using on my site: Here Please disregard the HTML and focus only on the CSS as that&apo ...

What could be the reason for the image not aligning to the middle with vertical-align?

I'm facing an issue with the alignment of images on my website. The images are currently displayed from the top, but I would like them to be aligned in the middle vertically. However, using the 'vertical-align: middle' property on the images ...

JavaScript framework that is easily customizable to include support for XmlHttpRequest.onprogress, even if it needs to be emulated

Which JavaScript library or framework offers support for the "onprogress" event for XmlHttpRequest, even if it needs to be emulated using a plugin or extension? Alternatively, which JavaScript framework is the most straightforward to extend in order to add ...

Incorporate an HTTP Header into a Wicket Ajax Request

I am trying to include a custom HTTP header in all Ajax (XHR) requests made by Wicket. I attempted the following: $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('X-My-Header', 'value'); } }); and $(doc ...

Issues with NodeJs Express routes execution

After testing, I found that only the default route "/" is working in my code. Many similar issues involve routers being mounted to paths like "/auth" or "/user". Even when I tested the default router mounted to "/", it still isn't functioning properly ...

Unable to direct to the main page in index.js of the next.js application

I have been working on a next.js application and encountered an issue with a component I created called <ButtonGroup>. I added a button with the code <Button href="index">Home</Button> to allow users to navigate back to the home ...

Making AngularJS 'PUT' requests: The process of submitting only the data in a form

I am facing an issue while updating user data in Angular. When I send a 'PUT' request, the entire user $scope is being sent instead of only the fields visible on the form. To retrieve and update the data, I am using a Factory. Below is my edit f ...

A guide on utilizing express.js to retrieve and display the output of a mySql query

I am facing an issue with getting the results of my simple SELECT command into the index.js file. I want to store all the records in an array, but when I try to do so, I always end up with undefined values. Interestingly, if I print the results in the data ...

Transmitting data to the server side using JavaScript for each request

Looking for a solution to send additional information with each AJAX request from my JavaScript application, without using QueryString or Headers. The aim is to keep this information abstract from the user and ensure it's session-specific by destroyin ...

Is it possible to access the service and 'self' directly from the HTML template?

When working with Angular 6, one method to access component properties from a service is to pass 'self' to the service directly from the component. An example of this implementation is shown below: myComponent.ts public myButton; constructor(p ...

What is the best way to use ajax to append a value to an input if it is empty, or add a comma with

I recently came across this answer and implemented the following code: Here is the Ajax receiver: success: function(data) { jQuery("#assigncat").val(function(i,val) { return val + (val ? '' : ', ') + data.cat_id; ...

Restricting slash commands in Discord.js to a specific permission level

I'm currently developing a purge command, and I'm struggling to restrict its usage to users with the MANAGE_MESSAGES permission. Below is the source code for the client.on("ready") section as well as the entire command logic. Any assistance on ...

Attempting to eliminate a specific row within a table using HTML and JavaScript

Programming with JavaScript function removeElement(el) { el.parentElement.remove(); } document.getElementById('myButton').onclick = function () { const name = document.getElementById('name').value; const date = document.getElementById( ...

The onchange function in JavaScript is malfunctioning

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Product page</title> <!-- Fonts -- ...

What steps do I need to take in order to activate the server-side console logging?

Recently, I created some server middleware in my api/index.js file: module.exports = function(req, res, next){ console.log(req); next(); }; After that, I integrated it into my nuxt.config.js: serverMiddleware: [{path: 'stocks', handler ...

How come changes to the DOM are not recognized by subsequent DOM readings?

As I work on my Vue application, I have encountered a scenario involving an element with a data-range attribute defined as follows: :data-range="form.appearence.height_min + '/7'" The value of form.appearance.height_min is dependent on ...