简体   繁体   中英

Hide a javascript created div until all content is rendered

So I have a mobile webpage that needs to get some content from the web to be displayed in a modal. The modal itself is created via Javascript which is a div container which is set to display:none when closed.

<body>

  Display this content: 
    <button onclick="displayModal()">display</button>

  <script type="text/javascript">
     var htmlContents = "<div>some pretty heavy content</div>";
     var modal = //some code to create the modal div element.
     modal.style.display = 'none';

     function displayModal() {
         modal.innerHTML = htmlContents;
         modal.style.display = 'block';
     }
  </script>

</body>

Then the user clicks a button, then we populate the innerHTML of the div with some HTML and then switch the modal to display: block

The problem here is that the contents we're adding to innerHTML may be pretty heavy. Lots of images and css which may take some time to render (1 or 2 seconds on old devices). However, they start poping up into the view one by one. So the user may see images and divs out of place while things render.

Is there any way to switch the modal to visible ONLY after all the contents have been rendered offscreen.

PS: This is written on pure javascript (no jquery or any other library since performance is a concern).

I think there are a couple of ways you could do this. I think if you move the modal.innerHTML = htmlContents out of the displayModal() function you could get the images and modal contents to load before the user clicks on it. So it would look like this:

<body>

  Display this content: 
    <button onclick="displayModal()">display</button>

  <script type="text/javascript">
     var htmlContents = "<div>some pretty heavy content</div>";
     var modal = //some code to create the modal div element.
     modal.style.display = 'none';
     modal.innerHTML = htmlContents;

     function displayModal() {
         modal.style.display = 'block';
     }
  </script>

</body>

I also found this jQuery library that may help, it seems like a lot of people are using it: https://github.com/desandro/imagesloaded

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