Asynchronous image loading problem

+1 Shane Kelly · July 19, 2014
I'm creating a Hangman game for a project. I have most of the functionality I need, however I am having one issue. When the last incorrect guess is made, it displays the alert box telling you you've lost, before loading the image. I want the image to load first and then the alert box. 

I have spent some time trying to get this working and have read a good bit online but just can't seem to get it working. I realise that the issue is with the way the DOM loads elements and that I should create a callback function in Jquery. I have no real knowledge of Jquery, so it's probably this that's letting me down.

This is the line in my code that changes the image, and it works fine until it gets to the last one.

document.getElementById("gallows").src = displayGallows[incorrectGuesses - 1];

I have tried using a Jquery function to get this working but my knowledge of Jquery is pretty much non-existent.

var img = $("gallows");
img.load(function() {
alert("Unlucky, you lost. Better luck next time!");
img.src = displayGallows[incorrectGuesses - 1];

I have compared this to many posts I have found online and to my untrained eye, it looks ok. When I was troubleshooting I did realise that the img.src was assigned the correct value but the image didn't appear on my page or didn't fire the alert box.

This led me to believe that it may be an issue with linking to the jquery.js file. I have an HTML page that references the jquery file in it's head tag.

<link rel="stylesheet" href="base.css"/>
<script src="jquery.js"></script>
<script src="hangman.js"></script>
<script src="home.js"></script>

The file I am writing my javascript and jquery from is the hangman.js file.

Do I also need to refer to the jquery.js file from the hangman.js file? While reading up on this I found that I may have to do this, so I've tried this: 

///<reference path="jquery.js" />

and this

var jq = document.createElement('script');
jq.src = 'jquery.js';

but to no avail, though I don't really understand the second one! I found these examples in the dark recesses of the internet!!

Note that in my home.js file I have simple a simple jquery function to em-bold the text on a button when you mouseover it and this works ok. 

If anyone could help me out or point me in the right direction that would be great. I have been banging my head against the wall trying to get this to work!

Post a Reply


Oldest  Newest  Rating
0 Steven the awesome · July 22, 2014
I don't know if you already figured it out, but I'll show you something. So you want first load the picture and then the alert box? You can do this with JQuery as you may know.

$(document).ready(function(){        //this loads the page first and then the alert box.

     window.alert("He this is a message");

  • 1



A scripting language that is added to standard HTML to create interactive effects, apps, games for the browser.