Note that there are some explanatory texts on larger screens.

plurals
  1. POPreloading sounds and images in JQuery. It usually works but sometimes freezes, and I would appreciate advice on improving my code
    text
    copied!<p>This is my first time asking a question on this website which I have grown to love. I am trying to make games with JQuery and I need to preload sounds and images. If the images and sounds are already in the cache of the browser, it seems to work every time, but if they are not already in the cache of the browser, sometimes it freezes in the middle of loading, especially on Firefox. My question is, what is causing this to happen and how can I prevent it from happening? Refreshing the page usually solves the problem but I would like it to work flawlessly the first time if possible. Here's my code:</p> <p>HTML:</p> <pre><code>&lt;div id='loading_screen'&gt;Loading &lt;span id='how_much_loaded'&gt;0&lt;/span&gt;%&lt;/div&gt; &lt;div id='content'&gt;This is the content&lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>#content{opacity:0} #loading_screen{position:absolute;left:0px;top:0px} </code></pre> <p>Javascript:</p> <pre><code>var sounds=["sound0.wav","sound1.wav","sound2.wav","sound3.wav","sound4.wav","sound5.wav","sound6.wav","ding.wav"] var images=["background-3_blue.jpg","background-3_green.jpg","background-3_yellow.jpg","background-3_red.jpg","play2train.png"] var loaded_items=0; var total_items=sounds.length+images.length; function preload() { for (var index=0;index&lt;images.length;index++) { $("#preload").append( $("&lt;img /&gt;").attr({ src: images[index], onload: "counter();", style: "display:none"}) ) } for (var index=0;index&lt;sounds.length;index++) { $("#preload").append( $("&lt;audio /&gt;").attr({ src: sounds[index], oncanplaythrough='counter()', style: "display:none"}) ) } } function counter() { loaded_items++; $("#how_much_loaded").html((Math.round(loaded_items/total_items*100))) if (loaded_items==total_items) { $("#loading_screen").remove(); $("#content").animate({"opacity":1}); } } </code></pre> <p><a href="http://nickmanningwebdev.com/zero_through_nine_nov25/zero_through_nine.html" rel="nofollow">Here's the game I'm working on. See if it works on your computer</a>. Thanks!!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload