Home > Enterprise >  Wait for specific image resource to be downloaded/loaded and not execute any following javascript co
Wait for specific image resource to be downloaded/loaded and not execute any following javascript co

Time:12-07

I have some <img> tags and some <div> tags with 'background: url('example.jpg'); And I want to wait until these images are downloaded and not execute any following javascript code ultil these images are downloaded and loaded. So only after I can call a function to deactivate my website loader and keep adding the other scripts for animating and stuff...

PS: I don't want to wait ultil all images are loaded cause that will take too long, i just want some images (like the first background) to be loaded before I deactivate my website loader...

CodePudding user response:

You could load it into memory first then apply it to the element

var img = new Image();
img.onload = function() {
  console.log('image loaded');
  document.querySelector('div.bg').style.backgroundImage = `url(${img.src})`
}
img.src = "https://picsum.photos/200/300?"   new Date().getTime();
div.bg {
  height: 500px;
  width: 600px;
  background: #000;
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
}
<div class='bg'></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Javascript-beginner here, so I don't know if there are any existing functions or anything that might take care of this for you.

My search-results came empty-handed to your specific question, so this is what I would do if I was sure there is nothing out there:

  • periodically check whether a number of images already have a size.

Should be easy enough to build a dynamic list, or to specify a few specific images you want to load, I guess.

  • Related