Home > Enterprise >  How to preload full page background image without it flickering?
How to preload full page background image without it flickering?

Time:02-02

I am trying to load a simple webpage that has an image that covers the entire page background. However, when the page is first loaded, there is a noticeable white flickering for a split second as the image is being loaded. I have already tried suggestions such as but to no effect. Here is my code below:

<!DOCTYPE html>
<html>
  <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
  body, html {
    height: 100%;
    margin: 0;
  }

  .bg {
    /* The image used */
    background-image: url("img_girl.jpg");

    /* Full height */
    height: 100%; 

    /* Center and scale the image nicely */
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
  }
  </style>
  </head>
  
  <body>
    <div ></div>
  </body>
</html>

Does anybody have a solution to remove the flickering effect?

CodePudding user response:

You can set .bg with opacity 0, then with jQuery once the page is done loading add a class set with opacity 1.

If you want a "fadein" effect simply add a transition.

<!DOCTYPE html>
<html>
  <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
  body, html {
    height: 100%;
    margin: 0;
  }

  .bg {
    /* The image used */
    background-image: url("img_girl.jpg");

    /* Full height */
    height: 100%;

    /* Center and scale the image nicely */
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    transition: opacity 1.3s ease-out;
    opacity: 0;
  }

  .bg.visible{
    opacity: 1;
  }

  </style>
  </head>

  <body>
    <div ></div>
  </body>
  <script type="text/javascript">
    $(document).ready(function(){
      $(window).on("load",function(){
        $('.bg').addClass('visible');
      });
    });
  </script>
</html>

Maybe not the best solution but it works for me.

CodePudding user response:

If you want an image that covers the entire page background, you should directly set it for the <body> element like this:

body {
  background-image: url(your_url/your_image.png);
  background-position: center; // to center the image
  background-repeat: no-repeat; // to not repeat the image 
  background-size: cover; // to cover the element
  background-color: #000; // fallback if the image is not available
}

or with the CSS shorthand more compact:

background: #000 url(your_url/your_image.png) no-repeat center;
background-size: cover;
  •  Tags:  
  • Related