How can I leave a function start, only when another function has started completely?

advertisements

I have a problem. I have a fullscreen (not background! only for my intro on my onepage website.) image slide. (Created with backstretch, the real jQuery code is in an other .js file.) You'll see it in the code below. Now I have a problem. I've put text in the center over it which has the same cycle duration, so that it is changing the image at the same time as the text does. But when I upload the webpage to a server, the image is loading slower than the text. The result is, that the Text cycle starts before the image slider. Can I make a function, so that the text only starts cycling, when the image cycle has begun? I have already tried the "unload" function, but then the image is faster than the text. (It would also be okay to include a loading wheel when I open the website, so that the whole site can load.. Tell me if you don't understand what I mean)

    <!-- Intro Header -->
<header class="intro">
    <!-- Backstretch JS -->
  <!-- <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> -->
    <script src="js/jquery-1.11.2.min.js" type="text/javascript"></script>
  <script src="js/jquery.backstretch.js"></script> <script>
$.backstretch([
"images/myimage1.png",
"images/myimage2.png",
"images/myimage3.png",
"images/myimage4.png"
], {
fade: 750,       //Speed of Fade
duration: 5000     //Time of image display
});
</script>

<div class="brand-heading">
<script src="http://code.jquery.com/jquery-1.7.min.js"></script>
<script>
$(function () {
    var messages = [],
        index = 0;

    messages.push('Message 1');
    messages.push('Message 2');
    messages.push('Message 3');

    function cycle() {
        $('#some-id').html(messages[index]);
        index++;

        if (index === messages.length) {
            index = 0;
        }

        setTimeout(cycle, 5750);
    }

    cycle();
});
</script>
<div id="some-id"></div>
</div>
</header>

Use the properties complete and naturalWidth for checking the image is loaded.

It's quite simple. Check if complete and naturalWidth is > 0: image ok.

function IsImageOk(img) {

   if (!img.complete) {
      return false;
   }

   if (typeof img.naturalWidth !== "undefined" && img.naturalWidth === 0) {
      return false;
   }

   return true;
}

Read more here: Check if an image is loaded (no errors) in JavaScript