简体   繁体   中英

Display website once all images are ready to display

I use this code to animate opacity of the whole website.

HTML
<body>
        <script>document.body.className += ' fade-out';</script>
...
</body>

JS
$(function(){
            $('body').removeClass('fade-out');
});

CSS:
body{
  transition:1s all;
}
body.fade-out {
    opacity: 0;
    transition: none;
}

Take this pen for example: https://codepen.io/timsim/pen/bWOoYr

This animates the websites opacity, but it doesn't wait for all images to be ready to display. Whole website is changing opacity, and then the image jumps in. Not nice at all. this only happen the first time the website is loaded.

i would like to trigger body opacity animation when the images are ready to display. window.onload does not seem to be the correct place. How would you do that?

Wrap your jQuery code inside:

$(window).on("load", function() {
});

And don't use the $(document).ready();

The DOM is ready also when images are not loaded. The on load will be triggered once images will finish to be downloaded. So in your case:

$(window).on("load", function() {
  $('body').removeClass('fade-out');
});

This should do what you are looking for

You could create a function to preload the images. Then once each one has loaded you could remove the class.

const images = ['https://pbs.twimg.com/media/C7gflT8XUAAhsHm.jpg'];

function loadImg(img) {
  return new Promise((resolve, reject) => {
    const imgEl = document.createElement('img');
    imgEl.addEventListener('load', () => {
      resolve();
    });
    imgEl.src = img;
  });
}

function loadAll(imageArr) {
  const promises = imageArr.map(img => loadImg(img));
  Promise.all(promises).then(() => {
    document.querySelector('body').classList.remove('fade-out');
  });
}

loadAll(images);

I think setTimeout will be a good choice:

$(function(){
            $('body').setTimeout(removeClass('fade-out'), 3000);
});

that will delay fade out by 3 seconds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM